Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use prepared statements with Postgres

I know that I need prepared statements because I make more than one call to my database during one script.

I would like to get concrete examples about the following sentence

Look at typecasting, validating and sanitizing variables and using PDO with prepared statements.

I know what he mean by validating and sanitizing variables. However, I am not completely sure about prepared statements. How do we prepare statements? By filters, that is by sanitizing? Or by some PDO layer? What is the definition of the layer?

What do prepared statements mean in the statement? Please, use concrete examples.

like image 573
Léo Léopold Hertz 준영 Avatar asked Aug 07 '09 22:08

Léo Léopold Hertz 준영


People also ask

Can we use prepared statement for stored procedure?

If we want to use prepared statements in a stored procedure then it must be written inside the BEGIN and END block. To understand it, we are creating an example with the help of which we can get all the records from a table by passing the name of the table as a parameter of the stored procedure.

What is prepared statement in PostgreSQL?

A prepared statement is a server-side object that can be used to optimize performance. When the PREPARE statement is executed, the specified statement is parsed, analyzed, and rewritten. When an EXECUTE command is subsequently issued, the prepared statement is planned and executed.


1 Answers

What do prepared statements mean in the statement?

From the documentation:

This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.

See pg_prepare

Example from the page linked above:

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>

The MySQL documentation for Prepared Statements nicely answers the following questions:

  • Why use prepared statements?
  • When should you use prepared statements?
like image 134
karim79 Avatar answered Oct 12 '22 14:10

karim79