如何将参数绑定到mysqli查询?

时间:2015-10-07 16:37:35

标签: php mysqli

我写了以下代码:

$date = new DateTime();
$xxxxx= $date->getTimestamp(); 

if ($result = $mysqli->query("SELECT text_content, text_duration, start_time from texts WHERE start_time > xxxxx order by start_time asc")) {

while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
    }
    echo json_encode($myArray);
}

现在 - 如何以最有效的方式将xxxxx替换为启动时间?

2 个答案:

答案 0 :(得分:4)

请看一下: http://php.net/manual/en/mysqli-stmt.bind-param.php

$date = new DateTime();
$xxxxx = $date->getTimestamp();

$sql = "SELECT text_content, text_duration, start_time from texts WHERE start_time > ? order by start_time asc";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $xxxxx);
$stmt->execute();
$result = $stmt->execute();

然后在结果中使用json_encode

echo json_encode($result);

答案 1 :(得分:1)

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

$ts   = time();
$sql  = "SELECT text_content, text_duration, start_time from texts 
         WHERE start_time > ? order by start_time asc";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $ts);
$stmt->execute();
$stmt->get_result()->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);