php 如何处理mysql查询中的单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8490680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can handle single quote in mysql query
提问by Pushpendra Kuntal
i am working in php. i want to write query like this:-
我在 php 工作。我想写这样的查询:-
update user_account set university_name='St. Josed father's institute'
where userId=5;
but this is creating error due to 'smeans it creating problem because of single quote '.
但这是由于'造成错误,这意味着由于单引号'会产生问题。
please suggest me how can i handle this. currently i am right this directly St. Josed father's institutebut in my php code this is in variable $university_name
请建议我如何处理这个问题。目前我是对的,这直接是St. Josed 父亲的研究所,但在我的 php 代码中,这是在变量 $university_name 中
so please suggest me how can i check and remove such type of problem.
所以请建议我如何检查和消除此类问题。
回答by abcde123483
$location = "St. Josed father's institute";
$location = mysql_real_escape_string($location);
回答by D. Rattansingh
$query = update user_account set university_name='St. Josed father's institute'
where userId=5;
$query = str_replace("'","''", $query);
It's necessary that you realise this issue centers around SQL and not php. SQL's escape character (according to the standard 92) is '. So what we want to do is change
您有必要意识到这个问题是围绕 SQL 而不是 php。SQL 的转义字符(根据标准 92)是 '. 所以我们要做的是改变
'St. Josed father's institute' to 'St. Josed father''s institute'
'英石。Josed 父亲的研究所'到'圣。约瑟夫父亲的研究所
Using the escape character, mysql would not interpret you ' as the end of the string.
使用转义字符,mysql 不会将您 ' 解释为字符串的结尾。
回答by Frank Fang
you could use php function mysql_real_escape_string
你可以使用 php 函数 mysql_real_escape_string
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>
document is here: http://php.net/manual/en/function.mysql-real-escape-string.php
文档在这里:http: //php.net/manual/en/function.mysql-real-escape-string.php