Wednesday 11 July 2018

PHP PDO: POSITIONAL AND NAMED PLACEHOLDERS

PHP PDO: POSITIONAL AND NAMED PLACEHOLDERS

We had known about prepare statement from previous post. Now, we talk deeper about placeholder.

POSITIONAL PLACEHOLDERS

Give attention to this query:
$title = ‘PHP%’;
$author = ‘Bobi%’;
// query
$sql = “SELECT * FROM books WHERE title like ? AND author like ? “;
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
The query above used question marks to designate the position of values in the prepared statement. These question marks are called positional placeholders. We must take care of proper order of the elements in the array that we are passing to the PDOStatement::execute() method.

NAMED PLACEHOLDERS

Give attention to this query:
$title = ‘PHP%’;
$author = ‘Bobi%’;
// query
$sql = “SELECT * FROM books WHERE title like :title AND author like :author “;
$q = $conn->prepare($sql);
$q->execute(array(‘:author’=>$author,
‘:title’=>$title));
This use descriptive names preceded by a colon, instead of question marks. We don’t care about position/order of value. That’s why it called named placeholders.

0 comments:

Post a Comment