How can the mysql_error() function be used to troubleshoot PHP scripts?

The mysql_error() function can be used to retrieve the error message generated by a MySQL function call in PHP. This can be helpful in troubleshooting PHP scripts by providing more information about what went wrong during database operations. By checking the error message returned by mysql_error(), developers can identify and address issues such as incorrect SQL queries, database connection problems, or data validation errors.

// Example of using mysql_error() to troubleshoot PHP scripts
$conn = mysqli_connect("localhost", "username", "password", "database");

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

$query = "SELECT * FROM non_existent_table";
$result = mysqli_query($conn, $query);

if (!$result) {
    echo "Error: " . mysqli_error($conn);
}

mysqli_close($conn);