Understanding Prepared Statements in PHP and MySQL

Sohel Ahmed
3 min readMay 21, 2024

--

I recently came across a question online: “How does Laravel prevent SQL injection?” In my search for an answer, I discovered that prepared statements are a key method for preventing SQL injection in Laravel and other frameworks. This powerful feature enhances the security and efficiency of database interactions. Let’s dive into what prepared statements are, their benefits, and how to implement them in PHP and MySQL.

What are Prepared Statements?

Prepared statement is a feature used in database management systems to execute the same SQL statement repeatedly with high efficiency.

How prepared statements actually work?

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?”). Example: INSERT INTO Users VALUES(?, ?, ?)
  2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
  3. Execute: At a later time, 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

Benefits of Prepared Statements

  1. Security Against SQL Injection: SQL injection is a common attack vector where malicious users can manipulate SQL queries by injecting malicious code. Prepared statements mitigate this risk by treating query parameters as data rather than executable code. This separation ensures that user input cannot alter the intended query structure.
  2. Performance Improvements: When a prepared statement is executed multiple times, the database server only needs to parse and compile the query once. Subsequent executions reuse the compiled query. We only need to send the parameters each time, not the whole query, which can significantly minimize bandwidth to the server and improve performance, especially for complex queries.

Implementing Prepared Statements in PHP and MySQL

To implement prepared statements in PHP with MySQL, you typically use the mysqli or PDO extensions. Below, we'll explore both methods.

Using mysqli

  1. Establish a Database Connection:
$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);
}

2. Prepare the SQL Statement:

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");

3. Bind Parameters:

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

Here, the “s” specifies that the parameter is a string. Other types include “i” for integer, “d” for double, and “b” for blobs.

4. Execute the Statement:

// 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();

5. Fetch the Results:

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process each row
}
//close connection
$stmt->close();
$conn->close();

Using PDO

  1. Establish a Database Connection:
$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);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}

2. Prepare the SQL Statement:

 $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");

3. Bind Parameters:

$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

4. Execute the Statement:

  // 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();

5. Fetch the Results:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// Process each row
}
//close connection
$conn = null;

Conclusion

Prepared statements are a robust feature for interacting with databases in PHP and MySQL. They offer enhanced security against SQL injection, improved performance, and cleaner code. Moreover, their utility extends beyond PHP to many other programming languages, making them a critical tool for secure and efficient database management. Whether you are using mysqli, PDO, or another language like Python or Java, understanding and implementing prepared statements is essential for any developer.

--

--