Instance
Add a backslash before each double quotation mark ("):
<?php $str = addslashes (' What does ' yolo ' mean? '); Echo ($STR);?>
Definition and usage
The Addslashes () function returns a string that adds a backslash before a predefined character.
The predefined characters are:
Single quotation mark (')
Double quotation marks (")
Back slash (\)
Null
Tip: This function can be used to prepare the appropriate string for strings stored in the database and for database query statements.
Note: By default, PHP instruction MAGIC_QUOTES_GPC is on, and automatically runs Addslashes () for all GET, POST, and COOKIE data. Do not use Addslashes () for strings that have been MAGIC_QUOTES_GPC escaped, because this results in double-layer escaping. You can use the function GET_MAGIC_QUOTES_GPC () to detect this situation.
Grammar
Addslashes (String)
Parameters |
Describe |
String |
Necessary. Specifies the string to be escaped. |
Technical details
return value: |
Returns the escaped string. |
PHP version: |
4 + |
More examples
To add a backslash to a predefined character in a string:
<?php$str = "Who ' s Peter Griffin?"; Echo $str. "This was not safe in a database query.<br>"; Echo addslashes ($STR). "This is safe in a database query."? >
The purpose of the PHP addslashes function is to precede pre-defined characters with backslashes, which include the following predefined characters:
Single quotation mark (')
Double quotation marks (")
Back slash (\)
Null
The Addslashes function is often used when inserting data into a database, such as having a string
$str = "My name ' s WXP";
Now we're going to insert this string into the database table, because the string has single quotes ', which is likely to conflict with the single quotation mark of the MySQL concatenation string, which causes the SQL statement to be incorrect, and the insert operation cannot be performed properly, we need to use the Addslashes function to process the string. Such as:
$str = "My name ' s WXP"; Echo addslashes ($STR);//Output my name\ ' s WXP
Then in the stitching MySQL string:
$sql = "INSERT into student (Student_name) VALUES ('". Addslashes ($STR). "')"; mysql_query ($sql);
Now that the string is inserted into the database, do you know whether the inserted string is a backslash or a backslash? I'm afraid a lot of people will think it must be a string with a backslash. In fact, the answer is wrong, the inserted string is no backslash. As to why the inserted string does not have a backslash in the database, please continue to see the following explanation.
If the string $str= "My name ' s WXP" is data submitted using post and get, the data inserted into the database is a backslash, so addslashes inserts the backslash into the database only when the post and get data are inserted into the database. In other cases, backslashes are not inserted into the database.