Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO prepared statements

Tags:

php

mysql

pdo

I was told today that I should really be using PDO and prepared statements in my application. Whilst I understand the benefits, I am struggling to understand how I implement them into my workflow. Aside from the fact that it makes code much cleaner, should I have a specific database class which houses all my prepared statements or should I create one each time I want to run a query? I'm finding it very hard to understand when I should use a standard PDO query and when I should use a prepared statement. Any examples, tips or tutorial links would be greatly appreciated.

like image 746
Hanpan Avatar asked Sep 21 '09 22:09

Hanpan


People also ask

What is PDO prepared statement?

In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.

What is prepare in PDO PHP?

PDO::prepare — Prepares a statement for execution and returns a statement object.

What is a prepared statement in PHP?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").

Does PDO prepare prevent SQL injection?

The short answer is NO, PDO prepares will not defend you from all possible SQL-Injection attacks.


1 Answers

There are two great examples on the pdo::prepare() documentation.

I have included them here and simplified them a bit.

This one uses ? parameters. $dbh is basically a PDO object. And what you are doing is putting the values 150 and 'red' into the first and second question mark respectively.

/* Execute a prepared statement by passing an array of values */ $sth = $dbh->prepare('SELECT name, colour, calories                       FROM fruit                       WHERE calories < ? AND colour = ?');  $sth->execute(array(150, 'red'));  $red = $sth->fetchAll(); 

This one uses named parameters and is a bit more complex.

/* Execute a prepared statement by passing an array of values */ $sql = 'SELECT name, colour, calories         FROM fruit         WHERE calories < :calories AND colour = :colour';  $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $sth->execute(array(':calories' => 150, ':colour' => 'red'));  $red = $sth->fetchAll(); 
like image 84
Ólafur Waage Avatar answered Sep 21 '22 23:09

Ólafur Waage