PHP Prepared Statements

Print

Somehow for web developers, doing a query can be more complicated if it should face a large amount of data since you may have to repeat the same query for several times. Therefore, if you would like to input a large amount of database into your query, you can try using prepared statements to optimize your query process and prevent hacker from corrupting your database through SQL injection method. Besides, in order to execute the same (or similar) SQL statement repeatedly with high efficiency, a prepared statement is the best feature for it which it basically works like this:

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?”). Example: INSERT INTO MyGuests VALUES(?,?,?)
  2. The query optimization on the SQL statement template are parsed, compiled, and performed by the database which in the end the result will be stored without the need to execute it.
  3. Execute: In the future, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values.

There are two main advantages that prepared statements can offer when it is compared to executing SQL statements directly:

  • This technique will be suitable if you wish to reduce parsing time since you only need to make the preparation on the query once.
  • As you need send only the parameters each time and not the whole query, bound parameters will minimize bandwidth to the server.
  • Because parameter values, which are transmitted later using a different protocol, need not be correctly escaped, prepared statements are very useful against SQL injections. Besides, SQL injection cannot occur if the original statements template is not derived from external input.

Prepared Statements in MySQLi

The following example uses prepared statements and bound parameters in MySQLi:

Example (MySQLi with Prepared Statements)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare(“INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)”);
$stmt->bind_param(“sss”, $firstname, $lastname, $email);

// set parameters and execute
$firstname = “John”

$lastname = “Doe”;
$email = “john@example.com”;
$stmt->execute();

$firstname = “Mary”;
$lastname = “Moe”;
$email = “mary@example.com”;
$stmt->execute();

$firstname = “Julie”;
$lastname = “Dooley”;
$email = “julie@example.com”;
$stmt->execute();

echo “New records created successfully”;

$stmt->close();
$conn->close();
?>

Code lines to explain from the example above:

“INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)”

We insert a question mark (?) in our SQL where we want to substitute in an integer, string, double or blob value.

Then, have a look at the bind_param() function:

$stmt->bind_param(“sss”, $firstname, $lastname, $email);

This function binds the parameters to the SQL query and tells the database what the parameters are. The “sss” argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.

The argument may be one of four types:

  • i-integer
  • d-double
  • s-string
  • b-BLOB

We must have one of these for each parameter. By telling mysql what type of data to expect, we minimize the risk of SQL injections.

Prepared Statements in PDO

The following example uses prepared statements and bound parameters in PDO:

Example (PDO with Prepared Statements)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDBPDO”;

try {
    $conn = new PDO(“mysql:host=$servername;dbname=$dbname”, $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 // prepare sql and bind parameters
    $stmt = $conn->prepare(“INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES (:firstname, :lastname, :email)”);
    $stmt->bindParam(‘:firstname’, $firstname);
    $stmt->bindParam(‘:lastname’, $lastname);
    $stmt->bindParam(‘:email’, $email);

    // insert a row
    $firstname = “John”;
    $lastname = “Doe”;
    $email = “john@example.com”;
    $stmt->execute();

    // insert another row
    $firstname = “Mary”;
    $lastname = “Moe”;
    $email = “mary@example.com”;
    $stmt->execute();

// insert another row
    $firstname = “Julie”;
    $lastname = “Dooley”;
    $email = “julie@example.com”;
    $stmt->execute();

    echo “New records created successfully”;
    }
catch(PDOException $e)
    {
    echo “Error: ” . $e->getMessage();
    }
$conn = null;
?>