How can the use of mysql_real_escape_string() and mysql_error() improve the security and error handling of PHP scripts?

Using mysql_real_escape_string() helps prevent SQL injection attacks by escaping special characters in a string before sending it to the database. This function ensures that user input is properly sanitized before being used in SQL queries. On the other hand, using mysql_error() allows for better error handling in PHP scripts by providing detailed error messages from MySQL, which can help in debugging and troubleshooting database-related issues.

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

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

// Sanitize user input
$name = mysqli_real_escape_string($connection, $_POST['name']);

// Perform SQL query
$sql = "INSERT INTO users (name) VALUES ('$name')";

if (mysqli_query($connection, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}

// Close connection
mysqli_close($connection);