How can error handling functions like mysql_error() be used effectively in PHP to troubleshoot database-related issues?

When troubleshooting database-related issues in PHP, error handling functions like mysql_error() can be used effectively to provide detailed error messages that can help identify and resolve the problem. By including these functions in your code, you can catch any errors that occur during database operations and display them to the user or log them for further analysis.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = mysqli_connect($servername, $username, $password, $dbname);

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

// Perform database operations
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);

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

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

// Close the connection
mysqli_close($conn);