What are the best practices for handling database operations in PHP to ensure successful execution and error handling?
When handling database operations in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, always check for errors after executing database queries and handle them appropriately to prevent unexpected behavior in your application.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute a SQL query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$user_id = 1;
$stmt->execute();
// Check for errors
if ($stmt->error) {
die("Error executing query: " . $stmt->error);
}
// Handle query results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the statement and connection
$stmt->close();
$conn->close();