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.
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND password = ?"); $pdo->bindParam(1, "email@example.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 firstname.lastname@example.org is assigned to the email(?) and like this password will be assigned to the password (?) placeholder. Then we will simply execute() the statement.
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND password = :password"); $pdo->bindParam(":email", "email@example.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.