prepared statement in php

To use prepared statements in PHP, you need to follow these steps:

  1. Create a database connection using mysqli or PDO
  2. Prepare the SQL statement with placeholders for the values you want to insert or select
  3. Bind the values to the placeholders using the appropriate method (bind_param for mysqli or bindValue/bindParam for PDO)
  4. Execute the prepared statement
  5. Fetch the results if you are selecting data

Here's an example of how to use prepared statements with mysqli:

main.php
// create db connection
$conn = new mysqli($servername, $username, $password, $dbname);

// prepare statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");

// bind parameter(s)
$username = "john";
$stmt->bind_param("s", $username);

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

// store result
$result = $stmt->get_result();

// fetch data
while ($row = $result->fetch_assoc()) {
    echo $row['username'] . "<br>";
}

// close statement and connection
$stmt->close();
$conn->close();
501 chars
25 lines

And here's an example of how to use prepared statements with PDO:

main.php
// create db connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// prepare statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");

// bind parameter(s)
$username = "john";
$stmt->bindParam(":username", $username);

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

// fetch data
while ($row = $stmt->fetch()) {
    echo $row['username'] . "<br>";
}

// close statement and connection
$stmt = null;
$conn = null;
472 chars
22 lines

gistlibby LogSnag