In the context of PHP and MySQL, what is the significance of using htmlspecialchars() versus mysql_escape_string() for data manipulation?
When dealing with user input that will be stored in a MySQL database, it is important to sanitize the data to prevent SQL injection attacks. The htmlspecialchars() function is used to convert special characters to HTML entities, making it safe to display user input on a webpage. On the other hand, the mysql_escape_string() function is used to escape special characters in a string before sending it to a MySQL database to prevent SQL injection attacks.
// Using htmlspecialchars() to sanitize user input before displaying on a webpage
$user_input = "<script>alert('XSS attack');</script>";
$sanitized_input = htmlspecialchars($user_input);
echo $sanitized_input;
// Using mysql_escape_string() to sanitize user input before storing in a MySQL database
$user_input = "'; DROP TABLE users; --";
$sanitized_input = mysql_escape_string($user_input);
// Inserting the sanitized input into the database
$query = "INSERT INTO table_name (column_name) VALUES ('$sanitized_input')";
mysqli_query($connection, $query);