正常查询准备语句

时间:2013-11-11 20:32:54

标签: mysqli prepared-statement

我目前正在使用数据库等。在一个页面上,我的代码看起来像这样。我知道如何做准备语句,但是无法弄清楚(在我的脑海中)如何更改此查询以及将什么放入bind_param和bind_result等。

任何帮助将不胜感激。这是我的代码:

$topDate = date('Y-m-d', strtotime('-1 week'));
$query = "SELECT *, DATEDIFF(ends, starts) as datedifference FROM news WHERE DATEDIFF(starts,'$topDate')>0 ORDER BY starts LIMIT 12;";
if ($result = mysqli_query($connection, $query)) {
    while ($row = mysqli_fetch_assoc($result)) {
        //What i do with my data
    }
}

1 个答案:

答案 0 :(得分:0)

+1使用预准备语句。

以下是您的代码作为预处理语句的示例(请记住,我不知道您的表结构是什么样的):

$connection = new mysqli(HOST,USER,PASSWORD,DATABASE);
$stmt = $connection->prepare("SELECT *, DATEDIFF(ends, starts) as datedifference FROM news WHERE DATEDIFF(starts,?)>0 ORDER BY starts LIMIT 12;");
$stmt->bind_param('s', $topDate);
$stmt->execute();
$stmt->bind_result($col1, $col2, $col3, $col4) //...etc, the number of variables here must match the column count;
if($stmt->num_rows > 0)
{
    while($stmt->fetch())
    {
        print("col1 = " . $col1, "col2 = " . $col2,"col3 = " . $col3,"col4 = " . $col4);
        //will bind the rows results to the $col variables on every pass.
    }



}

$stmt->close();