SQL查询中的PHP变量

时间:2013-03-21 14:30:02

标签: php sql

这是我的代码的一部分:

$sql = "select uid,connected,callerid2 from calls where uid = $uid;";
    $c = new dbConnect();
    $results = pg_query($c->pgConnect(), $sql);
    if (!$results)
    {
        die("Error in SQL query: " . pg_last_error());
    }

当我从SSH执行它时,会出现以下消息:

LINE 1: select uid,connected,callerid2 from calls where uid = ;

好像$uid没有正确注入,但我不确定原因。我也尝试了pg_prepare,结果相同。我需要做些什么不同的事情?

4 个答案:

答案 0 :(得分:1)

$sql = "select uid,connected,callerid2 from calls where uid = '" . $uid . "'";

并确保$uid存在。

答案 1 :(得分:1)

$sql = "select uid,connected,callerid2 from calls where uid = '" . (int)$uid . "'";

答案 2 :(得分:0)

$query = sprintf("select uid,connected,callerid2 from calls where uid = '%s'", 
$uid); 
// Then run the query. 
$result = mysql_query($query);

答案 3 :(得分:-2)

变量显然是空的。不混合字符串和变量总是好的

$sql = "select uid,connected,callerid2 from calls where uid = " . $uid . ";";

如果$uid应该是字符串而不是整数,请用引号括起来:

$sql = "select uid,connected,callerid2 from calls where uid = '" . $uid . "';";