addslashes() escapes quotes, backslashes and NUL with backslashes. Do not use it as SQL-injection protection; use prepared statements for database queries.
$text = "O'Reilly";
echo addslashes($text); // O\'Reilly
string addslashes ( string $string )
$string: The input string where special characters will be escaped by backslashes.$str = "John's book";
echo addslashes($str); // Output will add backslashes before the single quote
Output:
John\'s book
$str = 'He said, "It\'s a test!"';
echo addslashes($str); // Backslashes added before single and double quotes
Output:
He said, \"It\'s a test!\"
$str = "C:\\Program Files\\";
echo addslashes($str); // Backslashes are escaped too
Output:
C:\\Program Files\\
$str = "A NULL character \0 is here.";
echo "Output with echo: " . $str . "<BR>"; // NUL may not display visibly in ordinary output
// To display the full string, including the escaped NULL, we use var_dump
var_dump(addslashes($str));
Output:
Output with echo: A NULL character
string(28) "A NULL character \0 is here."
As you can see, the addslashes() function adds a backslash before the NULL character, but the regular `echo` only prints up to the NULL character. Using var_dump(), we can see the full string including the escaped NULL.
$name = "O'Reilly";
$stmt = $mysqli->prepare('SELECT * FROM users WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
The SQL value is bound separately instead of being inserted into the query string. Check errors and handle the result using your application's usual database flow.
addslashes() only for formats that explicitly require its escaping rules. Use prepared statements when querying a database, and htmlspecialchars() when safely displaying untrusted text in HTML.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.