What are best practices for debugging PHP code that involves database queries and updates?
When debugging PHP code that involves database queries and updates, it is essential to check for errors in the SQL syntax, connection to the database, and data being passed to the queries. One best practice is to use error reporting functions like `mysqli_error()` to display any errors that occur during the query execution. Additionally, logging SQL queries and results can help in identifying issues with the database interactions.
// Establish a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection is successful
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Sample query to retrieve data from a table
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Check for errors in the query execution
if (!$result) {
die("Error executing query: " . mysqli_error($connection));
}
// Fetch and display the results
while ($row = mysqli_fetch_assoc($result)) {
echo "User ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}
// Close the connection
mysqli_close($connection);