How can error handling, such as using mysql_error() function, be integrated into the PHP code to better troubleshoot issues with database queries and results?

When working with database queries in PHP, it is important to handle errors effectively to troubleshoot issues that may arise. One way to do this is by using the mysql_error() function to display any errors that occur during the execution of queries. By checking for errors after each query, you can quickly identify and address any issues with the database connection or query syntax.

// Connect to the 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));
}

// Process the results
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

// Close the connection
mysqli_close($connection);