为什么带单引号的字符串在插入数据库时会引发错误?
我的问题是:如何在字符串中允许单引号?
例如,我有一个表单和一个文本框。它被设置为允许用户输入他们的名字。从那里,它发布数据并将其输入数据库。
我需要能够允许使用单引号(撇号),因为有些人的名字中有撇号,例如“O'Reilly”。
有什么建议吗?
My question is: How do you allow single quotes in strings?
For example, I have a form, and a text box. It is set up to allow the user to enter their name. From there, it posts and feeds the data into a database.
I need to be able to allow single quotes (apostrophe) as some people's names have an apostrophe in their names, such as "O'Reilly".
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不以任何方式禁止单引号。我只是假设您将其插入数据库时出错。这可能是由于在输入值上省略了
mysql_real_escape_string()
。如果您尝试 INSERT ... ('O'Reilly'),您将收到 SQL 错误,这就是 SQL 转义函数的全部意义。
Single quotes are not forbidden in any way. I'll simply assume that you got an error inserting it into the database. This is likely due to the omission of
mysql_real_escape_string()
on input values.You will get an SQL error if you try
INSERT ... ('O'Reilly')
which is the whole point of the SQL escaping functions.对插入数据库的任何文本使用 mysql_real_escape_string() 函数。如果您将数据直接发布到数据库中,您的脚本中可能会出现错误,因为您实际上所做的是结束 MySQL 引用。
转义数据也是安全的必要条件。您应该拥有类似以下内容的内容:
Use the mysql_real_escape_string() function on any text that you insert into your database. You might be getting an error in your script if you are posting the data directly into your database because what you are actually doing is ending the MySQL quote.
It's also a security necessity that you escape your data. Something like the following is what you should have:
如果我正确地阅读你的问题,那么你已经在你的程序中编写了一个SQL注入错误,允许稍微恶意人员和病毒读取和写入您的数据库。 (想象一下有人在字段中输入
';drop table users;
...再见数据。)对抗 SQL 注入攻击的最简单方法是使用 准备好的语句,要求数据库安全地处理输入数据:
If I am reading your question correctly, you have coded an SQL Injection bug into your program, allowing slightly malicious people and viruses to read and write your database. (Imagine someone typing in
';drop table users;
into a field... goodbye data.)The easiest way to combat SQL Injection attacks is to write your SQL queries using prepared statements, which ask the database libraries to handle input data safely: