【问题标题】:Normal Query to Prepared Statement对准备好的语句的普通查询
【发布时间】:2013-11-11 20:32:54
【问题描述】:

我目前正在使用数据库等。在一页上我的代码看起来像这样。我知道如何做准备好的语句,但只是不知道(在我的脑海中)如何更改此查询以及在 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
    }
}

【问题讨论】:

    标签: mysqli prepared-statement


    【解决方案1】:

    +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();
    

    【讨论】:

    • 谢谢你:)。看起来是正确的,一旦我测试它是否有效,我会告诉你。
    猜你喜欢
    • 2010-12-23
    • 2011-09-12
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 2011-09-11
    相关资源
    最近更新 更多