xxxxxxxxxx
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
xxxxxxxxxx
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
xxxxxxxxxx
$stmt->bind_param("i", $data); // Type: Integer
$stmt->bind_param("d", $data); // Type: Double
$stmt->bind_param("s", $data); // Type: String
$stmt->bind_param("b", $data); // Type: Blob
xxxxxxxxxx
// Example code for using prepared statements in PHP
// 1. Establish a database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 2. Prepare the SQL statement
$stmt = $conn->prepare("SELECT * FROM your_table WHERE id = ?");
if (!$stmt) {
die("Prepare failed: " . $conn->error);
}
// 3. Bind parameters and execute the statement
$id = 1; // Example value
$stmt->bind_param("i", $id); // Assuming the ID column is of Integer type
if (!$stmt->execute()) {
die("Execute failed: " . $stmt->error);
}
// 4. Retrieve the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Access the retrieved data from the row
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . "<br>";
}
// 5. Close the statement and database connection
$stmt->close();
$conn->close();