What are the best practices for handling errors and debugging when using MySQL queries in PHP?

When handling errors and debugging with MySQL queries in PHP, it is important to use error handling functions such as mysqli_error() to catch and display any errors that may occur during query execution. Additionally, using prepared statements can help prevent SQL injection attacks and make debugging easier.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Perform a query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Check for errors
if (!$result) {
    die("Error: " . mysqli_error($connection));
}

// Fetch results
while ($row = mysqli_fetch_assoc($result)) {
    // Process results
}

// Close connection
mysqli_close($connection);