IDIOT DEVELOPER

Prepared Statement in PDO (PHP Data Object)
Prepared Statement in PDO (PHP Data Object)

A prepared statement is a precompiled SQL statement that can be executed multiple times by sending just the data to the server. It has the added advantage of automatically making the data used in the placeholders safe from SQL injection attacks.

 

Using prepared statements will help protect you from SQL injection.

 

PDO supports both positional or unnamed (?) and named (:names) placeholder. the names placeholder always begins with a colon(:) and rest can be written using letters, digits and underscores only. Quotes should not be used around placeholders.

 

We use prepare function of the PDO class to create prepared statements.

 

First we need to create an SQL statement with unnamed or named placeholder in it. Out of both any placeholder can be used. It’s up to you. Then we use bindParam function of the PDO class to assign value to these placeholders.

 

Unnamed placeholder

 


$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND password = ?");

$pdo->bindParam(1, "example@something.com");
$pdo->bindParam(2, "password");

$pdo->execute();

 

In this case we use number as the first parameter in the bindParam() and in second parameter we provide the value which we want to assign at that placeholder. Like example@something.com is assigned to the email(?) and like this password will be assigned to the password (?) placeholder. Then we will simply execute() the statement.

 

Named placeholder

 


$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND password = :password");

$pdo->bindParam(":email", "example@something.com");
$pdo->bindParam(":password", "password");

$pdo->execute();

 

In this case we have named starting with colon(:) sign. So the first parameter is the name starting with colon, and then the value in the bindParam() function, and the we will execute() the statement.

Leave a Reply

Your email address will not be published. Required fields are marked *