How can the use of mysql_error() help in troubleshooting issues with saving data in PHP scripts?

When saving data in PHP scripts, issues can arise due to syntax errors, connection problems, or data validation failures. By using the mysql_error() function, you can retrieve detailed error messages from MySQL, which can help you pinpoint the exact cause of the issue and troubleshoot it effectively.

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

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

// Your SQL query to save data
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";

// Execute the query
if (mysqli_query($connection, $sql)) {
    echo "Data saved successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}

// Close the connection
mysqli_close($connection);