How can the use of mysql_escape_string() or addslashes() functions help prevent SQL syntax errors in PHP database operations?

Using functions like mysql_escape_string() or addslashes() in PHP can help prevent SQL syntax errors by escaping special characters in user input before sending them to the database. This prevents malicious users from injecting SQL code into queries, which could potentially lead to data loss or unauthorized access to the database.

// Example of using mysql_escape_string() to prevent SQL injection
$user_input = "John O'Reilly";
$escaped_input = mysql_escape_string($user_input);

$query = "INSERT INTO users (name) VALUES ('$escaped_input')";
// Execute the query