HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP MySQL Prepared Statements

Prepared statements in PHP are a secure and efficient way to execute SQL queries with user-supplied input.


Here's how you can use prepared statements with MySQLi and PDO:

Using MySQLi Prepared Statements:

<?php

// MySQLi Configuration
$servername = "localhost"; // Change this to your MySQL server address
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to your MySQL database name

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

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

// Sample data
$name = "John Doe";
$email = "john@example.com";

// SQL statement with placeholders
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";

// Prepare the statement
$stmt = $conn->prepare($sql);

// Bind parameters to placeholders
$stmt->bind_param("ss", $name, $email);

// Execute the statement
if ($stmt->execute()) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error; } // Close statement and connection $stmt->close(); $conn->close(); ?>
You can click on above box to edit the code and run again.

Output

Using PDO Prepared Statements:

<?php

// PDO Configuration
$servername = "localhost"; // Change this to your MySQL server address
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to your MySQL database name

try {
    // Connect to MySQL using PDO
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    
    // Set PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Sample data
    $name = "John Doe";
    $email = "john@example.com";
    
    // SQL statement with named placeholders
    $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
    
    // Prepare the statement
    $stmt = $conn->prepare($sql);
    
    // Bind values to named placeholders
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    
    // Execute the statement
    if ($stmt->execute()) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "
" . $conn->errorInfo(); } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Close connection $conn = null; ?>
You can click on above box to edit the code and run again.

Output