PHP Prepared Statements


The Prepared Statement feature enables you to execute SQL commands efficiently.

 

  • Prevent SQL Injection
  • Improve performance for repeated queries
  • Safely bind variables without manually escaping strings

Syntax

1. Using MySQLi (Object-Oriented)

$conn = new mysqli("localhost", "root", "", "testdb");
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
 

2. Using PDO

$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);

Example

<?php
$conn = new mysqli("localhost", "root", "", "testdb");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];

    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email); // "ss" = string, string
    $stmt->execute();

    echo "User inserted successfully.";
    $stmt->close();
    $conn->close();
}
?>

<form method="POST">
    Name: <input type="text" name="name"><br><br>
    Email: <input type="email" name="email"><br><br>
    <input type="submit" value="Submit">
</form>

Advantage of Using Prepared Statements

Benefit Explanation
Security Protects against SQL injection
Performance SQL is parsed only once, reused multiple times
Readability Cleaner code and separation of logic
Flexibility Bind different types (int, string, etc.)



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.