I am trying to escape fields posted from a form. I can successfully insert into the SQL database by commenting out the code that escapes the string.
The error received is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\"test\",\"0123456789\",\"test@test.com\",\"1\",\"1\",\"fgsdfdfndfndfndfndfndfn\' at line 1
MikeW's solution worked. Also realized I was trying to escape the string before I had opened the database making mysqli_real_escape_string return null. Connecting to the database first, ($connect= new connect("server","user","password");) solved this problem. Hopefully this will help anyone else with the same problems.
解决方案
You should be using single quotes, not double quotes. Also, mysqli_real_escape_string() should be called on each variable, not on the query as a whole. You should get something like this:
However, for this sort of query you should consider using prepared statements.
其他提示
I'm not sure if MySQL works with double-quotes. You should use single-quotes. But the more glaring issue is that you need to call mysqli_real_escape_string() on every variable, not the entire query string.
To simplify the problem, say your query was as follows:
And then say I pass in a value, Michael O'Connor. What does your query become?
INSERT INTO tbl (Name) VALUES (\'Michael O\'Connor\')
Notice that not only did the ' in the actual name get escaped, but the quotes to surround that name also got escaped. If you called mysqli_real_escape_string() on the entire compiled query string, it has no way to distinguish a ' in the value vs. the ones that are supposed to surround the value.