Prepared statements help keep your database safe and make your code faster when running similar queries many times.
Prepared statements and why they matter in PHP
<?php // Prepare the SQL with placeholders $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email'); // Bind values to placeholders $stmt->bindParam(':email', $email); // Execute the statement $stmt->execute(); // Fetch results $results = $stmt->fetchAll(); ?>
Placeholders like :email are used instead of putting values directly in the query.
Binding values separately helps prevent harmful input from breaking your query.
<?php $stmt = $pdo->prepare('INSERT INTO users (name, age) VALUES (:name, :age)'); $stmt->execute(['name' => 'Alice', 'age' => 30]); ?>
<?php $stmt = $pdo->prepare('SELECT * FROM products WHERE price < ?'); $stmt->execute([100]); ?>
<?php $email = 'user@example.com'; $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email'); $stmt->bindParam(':email', $email); $stmt->execute(); ?>
This program creates a small database in memory, adds two users safely using prepared statements, then searches for one user by email and prints the result.
<?php // Connect to database using PDO $pdo = new PDO('sqlite::memory:'); // Create a simple table $pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)'); // Prepare an INSERT statement $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); // Insert two users safely $stmt->execute(['name' => 'John', 'email' => 'john@example.com']); $stmt->execute(['name' => 'Jane', 'email' => 'jane@example.com']); // Prepare a SELECT statement $select = $pdo->prepare('SELECT * FROM users WHERE email = :email'); // Search for Jane by email $searchEmail = 'jane@example.com'; $select->execute(['email' => $searchEmail]); // Fetch and print the result $user = $select->fetch(PDO::FETCH_ASSOC); if ($user) { echo "Found user: {$user['name']} with email {$user['email']}\n"; } else { echo "User not found.\n"; } ?>
Always use prepared statements when inserting or searching with user input to avoid security risks.
Prepared statements can improve performance if you run the same query many times with different data.
PDO is a common PHP extension that supports prepared statements with many databases.
Prepared statements separate SQL code from data to keep your database safe.
They help prevent hackers from changing your queries with bad input.
Using prepared statements is a best practice for working with databases in PHP.