What is the difference between addslashes() and mysql_real_escape_string() when sanitizing user input for database insertion in PHP?
When sanitizing user input for database insertion in PHP, it is important to prevent SQL injection attacks by escaping special characters. The addslashes() function escapes characters like quotes, backslashes, and null bytes, but it may not be sufficient to protect against all forms of SQL injection. On the other hand, mysql_real_escape_string() is specifically designed for escaping strings to be used in MySQL queries, providing more robust protection against SQL injection attacks.
// Using mysql_real_escape_string() to sanitize user input for database insertion
$input = $_POST['user_input'];
$escaped_input = mysql_real_escape_string($input);
// Insert escaped input into database
$query = "INSERT INTO table_name (column_name) VALUES ('$escaped_input')";
$result = mysql_query($query);
Related Questions
- In what ways can PHP switch statements be utilized to improve the functionality of the dynamic menu system described in the thread?
- How can sessions be used in PHP to control access to specific pages after password authentication?
- Are there any specific functions or libraries in PHP that are recommended for dealing with special characters in HTML?