如何在PHP中使用单引号(')来破坏字符串?

时间:2014-08-23 11:10:48

标签: php

这是我的代码:

   $newMsg="chinu debasish bitto deba prince's";

    //$curTime=date('G');
    //if(($curTime >= 9) || ($curTime < 21)){
        $chkUname=explode(" ",$newMsg);
        echo "SELECT mobile_hash FROM ".CHAT_USER." WHERE username IN(".implode(",",$chkUname).")";
    //}

上面的代码我得到了:

SELECT mobile_hash
FROM chat_users WHERE username IN(chinu,debasish,bitto,deba)

但我希望每个字符串都带有单引号,如:

SELECT mobile_hash
FROM chat_users WHERE username IN('chinu','debasish','bitto','deba') 

修改:这个问题不重复请再次查看我的问题并Formatting a PHP array for an SQL “IN” clause

2 个答案:

答案 0 :(得分:18)

使用 implode 构建格式化查询字符串值。由于您的字符串中包含撇号,因此您必须 escape 才能发出错误并且SQL注入攻击免费查询。

$imp = "'" . implode( "','", mysql_escape_string($chkUname) ) . "'";

echo "SELECT mobile_hash FROM ".CHAT_USER." WHERE username IN($imp)";

答案 1 :(得分:1)

foreach($chkUname as $i=>$v){
    $chkUname[$i]=addslashes($v); // or you can use *_real_escape_string()
}
echo "SELECT ... WHERE username IN('".implode("','",$chkUname)."')";