如何在mysql查询中处理单引号

时间:2011-12-13 14:16:26

标签: php mysql

我在php工作。我想写这样的查询: -

update user_account set university_name='St. Josed father's institute' 
where userId=5;

但由于而导致错误意味着因单引号'而产生问题。

请建议我如何处理这个问题。目前我是对的,直接圣。 Josed father's institute ,但在我的PHP代码中,这是变量 $ UNIVERSITY_NAME

所以请建议我如何检查并删除此类问题。

3 个答案:

答案 0 :(得分:11)

$location = "St. Josed father's institute";
$location = mysql_real_escape_string($location);

答案 1 :(得分:4)

$query = update user_account set university_name='St. Josed father's institute' 
where userId=5;

$query = str_replace("'","''", $query);

你必须意识到这个问题围绕SQL而不是php。 SQL的转义字符(根据标准92)是'。所以我们要做的就是改变

“圣Josed父亲的研究所'到'圣Josed father''sstitute'

使用转义字符,mysql不会将你解释为字符串的结尾。

答案 2 :(得分:3)

你可以使用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));
?>

文件在这里:http://php.net/manual/en/function.mysql-real-escape-string.php