将字符串插入 MySQL
我遇到了一个问题,我认为 MySQL 中的插入语句弄乱了输入数据库的字符串。
我在 PHP 代码中有一个像这样的插入语句:
$sql = 'insert into my_table ( numeric_id , string_value )
values ( '.$some_number.' , "'.$some_text.'" )';
当我稍后从数据库中获取 $some_text
时,它会弄乱字符串,例如 don\'t
而不是 don't 并将诸如 \r\n
之类的内容添加到输出中。
知道为什么会发生这种情况以及我应该改变什么吗?
I am running into a problem where I think my insert statement in MySQL is messing up the strings that get entered into the database.
I have an insert statement like this in PHP code:
$sql = 'insert into my_table ( numeric_id , string_value )
values ( '.$some_number.' , "'.$some_text.'" )';
And when later I get the $some_text
from the database, it messes up strings likedon\'t
instead of don't and ads things like \r\n
to the output.
Any idea why this is happening and what I should change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的某些代码进行了两次转义。
您只需要找到第二次执行此操作的代码并将其删除即可。
首先,您必须打印出变量才能查看其实际内容。
在盲目和基于假设的情况下,要理清事情是非常困难的。
只需在转义之前打印出
$some_text
变量即可查看。如果它已经转义了 - 那么在代码的前面的某个地方已经完成了额外的转义。Some of your code is doing escaping twice.
You just have to find the code that does it second time and get rid of it.
first of all you have to print out your variables to see it's actual contents.
It's hard as hell to sort out things being blinded and based on assumptions.
Just print out
$some_text
variable before escaping it and see. if it's already escaped - then additional escaping been done somewhere earlier in the code.始终使用准备好的语句将数据插入到 SQL 中。那么你根本不需要做任何转义。
Always use prepared statements to interpolate data into SQL. Then you don't have to do any escaping at all.
$sql = "插入 my_table (numeric_id, string_value) 值 ('$some_number', '$some_text')";
$query = mysql_query($sql);
/**
只需使用 (") 而不是 (');
*/
$sql = "insert into my_table (numeric_id, string_value) values ('$some_number' , '$some_text')";
$query = mysql_query($sql);
/**
just use (") instead of (');
*/
首先,转义您的输入:
其次,斜杠的问题可能是由于 PHP Magic Quotes 造成的。您可以在这里阅读更多相关信息: http://www.php.net /manual/en/security.magicquotes.disabling.php
您可以通过运行以下命令来检查魔术引号是否已打开:
如果已打开,您可以禁用它(如果您有权访问 php.ini)或者您可以使用 PHP 代码来解决魔术引号造成的问题:(
摘自 PHP.net)
First of all, escape your input:
Second, the issue with the slash is likely due to PHP Magic Quotes. You can read more about that here: http://www.php.net/manual/en/security.magicquotes.disabling.php
You can check if magic quotes is turned on by running this:
If it's on, you could either disable it (if you have access to php.ini) or you can use PHP code to fix the problem that magic quotes creates:
(taken from PHP.net)
这应该有效
this should work