PHP Basics
Functions in PHP
Working with Forms
Working with Files
Working with Databases
Advanced PHP Techniques

Prepared statements in PHP and SQL provide a way to safely execute SQL queries with dynamic input. They help prevent SQL injection attacks, improve performance, and make code more readable. Here’s a deep dive into how prepared statements work and how to use them effectively in PHP:

1. What are Prepared Statements?

Prepared statements are a feature of database management systems (DBMS) that allow SQL queries to be executed in a more secure and efficient way. A prepared statement involves two stages:

  • Preparation: The SQL query template is created with placeholders for input parameters.
  • Execution: The placeholders are replaced with actual values and the query is executed.

2. Why Use Prepared Statements?

  • Security: Prevents SQL injection attacks by ensuring that user input is treated as data and not executable code.
  • Performance: Improves performance for repeated queries as the preparation step is done only once.
  • Readability: Makes code cleaner and easier to maintain by separating the SQL logic from the data.

3. Using Prepared Statements in PHP

PHP provides two main extensions for working with databases and prepared statements: mysqli and PDO. Both support prepared statements, but PDO has the advantage of supporting multiple database systems.

3.1. Using mysqli

Here’s an example of how to use prepared statements with the ‘mysqli‘ extension:

				
					<?php
// Database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare the SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Check if preparation was successful
if ($stmt === false) {
    die("Prepare failed: " . $mysqli->error);
}

// Bind parameters (s for string)
$stmt->bind_param("s", $username);

// Set the parameter value
$username = "example_user";

// Execute the statement
$stmt->execute();

// Get the result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}

// Close the statement and connection
$stmt->close();
$mysqli->close();
?>

				
			

3.2. Using PDO

Here’s an example using the ‘PDO‘ extension:

				
					<?php
// Database connection
try {
    $pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Prepare the SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Set the parameter value
$username = "example_user";

// Bind parameters
$stmt->bindParam(":username", $username);

// Execute the statement
$stmt->execute();

// Fetch data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}

// Close the connection (optional, as PHP automatically closes the connection when the script ends)
$pdo = null;
?>

				
			

4. Placeholders in Prepared Statements

  • Positional Placeholders (Question Marks): Used in mysqli
				
					$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");

				
			
  • Named Placeholders (Colons): Used in PDO
				
					$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

				
			

5. Binding Parameters

  • mysqli: Uses the bind_param method. Each parameter type must be specified (s for string, i for integer, d for double, b for blob).
				
					$stmt->bind_param("s", $username);

				
			
  • PDO: Uses the bindParam or bindValue methods. Types are optional but can be specified using PDO::PARAM_* constants.
				
					$stmt->bindParam(":username", $username, PDO::PARAM_STR);

				
			

6. Error Handling

  • mysqli: Check for errors after each operation.
				
					if ($stmt === false) {
    die("Prepare failed: " . $mysqli->error);
}

				
			
  • PDO: Use exceptions to handle errors
				
					try {
    // Execute the statement
    $stmt->execute();
} catch (PDOException $e) {
    die("Execute failed: " . $e->getMessage());
}
try {
    // Execute the statement
    $stmt->execute();
} catch (PDOException $e) {
    die("Execute failed: " . $e->getMessage());
}

				
			

7. Fetching Results

  • mysqli: Use get_result and fetch the rows
				
					$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process row
}

				
			
  • PDO: Use fetch or fetchAll methods.
				
					while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Process row
}

				
			

8. Closing Statements and Connections

  • Always close the statement and connection when done:
  • ‘mysqli’
				
					$stmt->close();
$mysqli->close();

				
			
  • ‘PDO’
				
					$pdo = null;

				
			

Prepared statements are a powerful feature for building secure and efficient PHP applications that interact with databases. By using mysqli or PDO, you can take advantage of the benefits of prepared statements, such as preventing SQL injection, improving performance, and writing cleaner code.

Scroll to Top