When we need to use php to insert data containing special symbols, we will find that the data cannot be inserted normally, so how to solve it at this time? I encountered this problem at work recently, so I solved it by searching for information. Now I will share the solution with you. Friends in need can refer to it. Let's learn together.
Found the problem
When we write data to mysql, if there are special characters in the data, the data will not be stored properly. situation, for example:
mysql_query(”update table set `name`='make's'”);
At this time, theaddslashes()
function is generally used to escape the special characters in the data
Processing method
For the sake of security, PHP has introduced amagic_quotes_gpc = On
function, you can Single quotes can be directly inserted into the database without any processing. So when it comes to Off, you need to consider the issue of single quotes instead of blindly trusting the operating environment.
Whenmagic_quotes_gpc = On
, the processed data usingaddslashes()
will be saved in the database in the form of \'. If it is directly When outputting, you will find that there are more \ than you expected, sostripslashes()
appears, it can remove \ (different fromstr_replace("\", "",$ Str)
).
Whenmagic_quotes_gpc = Off
, the data processed usingaddslashes()
will be saved in the database in the form of ', without the above mentioned \ problem,addslashes()
plays the role of inserting data without errors. If it is output directly at this time, the data will be normal. No need to usestripslashes()
anymore.
addslashes()
andstripslashes()
are exactly the opposite. Direct memory:addslashes()
Add a \,stripslashes()
Go to one\
So when should I use it?
Simply put:
Whenmagic_quotes_gpc = On
, the system will automatically handle issues such as single quotes, whether to useaddslashes()
andstripslashes()
do not matter, but ifaddslashes()
is used when adding data, thenstripslashes()## must be used when displaying data
magic_quotes_gpc = Off, the system will not handle issues such as single quotes, so you must use
addslashes()when inserting data to display the data There is no need to use
stripslashes().
magic_quotes_gpcis On or Off, we use
addslashes()when adding data. When On ,
stripslashes()must be used, and
stripslashes()cannot be used when Off.
PHP implementation of time addition and subtraction function strtotime usage
phpHow to implement a simple web calculator function
PHP method to find the factorial of a number based on a recursive function
The above is the detailed content of How to insert data containing special symbols in php. For more information, please follow other related articles on the PHP Chinese website!