What are some best practices for handling database queries and result sets in PHP to avoid confusion and errors?
When handling database queries and result sets in PHP, it is important to properly structure your code to avoid confusion and errors. One best practice is to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, always check for errors after executing a query and handle them appropriately to provide meaningful feedback to the user.
// Example of using prepared statements to handle database queries in PHP
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Prepare a SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
// Bind parameters
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Check for errors
if($stmt->errorCode() !== '00000'){
// Handle errors
$errors = $stmt->errorInfo();
echo "Error: " . $errors[2];
} else {
// Fetch results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Process the result set
foreach($result as $row){
// Do something with the data
}
}