PHP:在sql查询中传递变量

时间:2015-03-30 16:39:07

标签: php mysql

我在PHP中有以下sql查询,输出为JSON:

<?php

$user_id = "1";

$sql = 'SELECT *,DATE_FORMAT(c.`date`, "%d.%m.%Y") AS date
          FROM
            conversation c,
            users u
          WHERE
            c.user_two = u.uid AND c.user_one = '$user_id'
            ORDER By  c.precious_time DESC';


$result = mysqli_query($con, $sql);

$rows = array();

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $rows [] = $row; 
}

mysqli_close($con);

echo json_encode($rows);

?>

当我执行php文件时,它不会回显任何内容,但如果我设置了c.user_one =&#34; 1&#34;而不是c.user_one =&#39; $ user_id&#39;然后它工作,它给了我结果。是否存在格式错误?

1 个答案:

答案 0 :(得分:0)

如果您使用双引号,它可以工作:

$sql = "SELECT *,DATE_FORMAT(c.`date`, '%d.%m.%Y') AS date
        FROM conversation c, users u
        WHERE c.user_two = u.uid AND c.user_one = '$user_id'
        ORDER By c.precious_time DESC";

仅供参考:http://php.net/manual/en/language.types.string.php#language.types.string.parsing