PHP只能在if语句中使用

时间:2015-10-07 02:45:48

标签: php

我的代码正常运行:

$menuArr

有时,查询会在foreach上找到结果,有时则没有。但是我不知道为什么如果查询没有找到结果apache仍然向我发送关于if中变量$productID = $_POST['productID']; $sql_product = "SELECT * FROM cc_menu_customizations WHERE cust_asoc= ?"; $stmt_product = $conn->prepare($sql_product); $sql_count="SELECT count(*) FROM cc_menu_customizations WHERE cust_asoc='$productID'"; $countResult = $conn->query($sql_count); if($countResult->fetchColumn() > 0) { $stmt_product->bindParam(':cust_asoc', $productID); $stmt_product->execute(array($productID)); $stmt_product->setFetchMode(PDO::FETCH_ASSOC); while($row = $stmt_product->fetch()) { $menuArr[$row['cust_title']][] = '<li class="item-inmodal-extra-wrap-options"><p>'. $row['cust_desc'] .'<p></li>'; } foreach($menuArr as $menuTitle => $productArr) { echo '<div class="item-inmodal-extra"><h3>'. $menuTitle .'</h3><ul class="item-inmodal-extra-wrap">'; foreach($productArr as $key =>$productname) { echo $productname; } echo '</ul></div>'; } } echo '<div class="item-inmodal-extra"> <h3>Special Instructions</h3> <textarea class="item-inmodal-extra s-intructions" placeholder="Please explicitly state any allergies you have. Requests incurring additional cost are fulfilled at merchant&#39;s discretion"></textarea> </div>'; 的错误不存在......

如果{{1}}语句为真,那么此变量不应仅处于活动状态吗?

修改

最终结果......更好?

{{1}}

1 个答案:

答案 0 :(得分:1)

除了安全问题,请回答下面的问题。您的评论者是正确的,您应该使用绑定参数并进行所有适当的清理,但这是另一个问题。

应该是:

<?php
$productID = $_POST['productID'];

$sql_product="SELECT * FROM cc_menu_customizations WHERE cust_asoc='$productID'";

$sql_count="SELECT count(*) FROM cc_menu_customizations WHERE cust_asoc='$productID'";
$countResult = $conn->query($sql_count)

if($countResult->fetchColumn() > 0) {
    $stmt_product = $conn->prepare($sql_product);
    $stmt_product->execute();           
    $result_product = $stmt_product->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $stmt_product->fetch()) {
        $menuArr[$row['cust_title']][] = '<li class="item-inmodal-extra-wrap-options"><p>'. $row['cust_desc'] .'<p></li>';
    }

    foreach($menuArr as $menuTitle => $productArr) {
        echo '<div class="item-inmodal-extra"><h3>'. $menuTitle .'</h3><ul class="item-inmodal-extra-wrap">';
        foreach($productArr as $key =>$productname) {
            echo $productname;
        }

        echo '</ul></div>';
    }
}

PDOStatement::rowCount

  

对于大多数数据库,PDOStatement :: rowCount()不返回受SELECT语句影响的行数。相反,使用PDO :: query()发出带有与预期SELECT语句相同的谓词的SELECT COUNT(*)语句,然后使用PDOStatement :: fetchColumn()来检索将返回的行数。然后,您的应用程序可以执行正确的操作。