验证没有投票PHP的消息时出错

时间:2017-10-20 15:20:47

标签: php mysqli

如果没有投票且所有同一打印零的查询我想显示错误消息,表示没有对此产品的投票。

问题是没有验证总是向我显示这样的消息,即实际上如果有投票,则该产品没有投票权。

如果没有产品投票,如何正确验证错误消息?

<?php
$id_product = "1";

    $stmtRating = $con->prepare("SELECT SUM(rating IN (4.5, 5))/COUNT(*)*100 AS pct_5_star,
       SUM(rating IN (3.5, 4))/COUNT(*)*100 AS pct_4_star,
       SUM(rating IN (2.5, 3))/COUNT(*)*100 AS pct_3_star,
       SUM(rating IN (1.5, 2))/COUNT(*)*100 AS pct_2_star,
       SUM(rating IN (0.5, 1))/COUNT(*)*100 AS pct_1_star,
       SUM(CASE WHEN rating IN (4.5, 5) THEN rating ELSE 0 END) AS in_5_star,
       SUM(CASE WHEN rating IN (3.5, 4) THEN rating ELSE 0 END) AS in_4_star,
       SUM(CASE WHEN rating IN (2.5, 3) THEN rating ELSE 0 END) AS in_3_star,
       SUM(CASE WHEN rating IN (1.5, 2) THEN rating ELSE 0 END) AS in_2_star,
       SUM(CASE WHEN rating IN (0.5, 1) THEN rating ELSE 0 END) AS in_1_star,
       AVG(rating) AS avg_rating,
       SUM(rating) as avg_total,
       COUNT(*) valuations
       FROM ratings
       WHERE id_product=?");


    $stmtRating->bind_param("i",$id_product);
    $stmtRating->execute();
    $stmtRating->bind_result(
        $pct_5_star,
        $pct_4_star,
        $pct_3_star,
        $pct_2_star,
        $pct_1_star,
        $in_5_star,
        $in_4_star,
        $in_3_star,
        $in_2_star,
        $in_1_star,
        $avg_rating,
        $avg_total,
        $valuations
    );

    //$stmtRating->fetch();
if ($stmtRating->num_rows>0) {
    while ($stmtRating->fetch()) {
      echo "$valuations <br>
      $pct_5_star <br>
      $pct_4_star <br>
      $pct_3_star <br>
      $pct_2_star <br>
      $pct_1_star <br>
      $in_5_star <br>
      $in_4_star <br>
      $in_3_star <br>
      $in_2_star <br>
      $in_1_star <br>
      $avg_rating <br>
      $avg_total <br>
      $valuations
";
    }
} else {
    echo "There are no votes for this product.";
}

1 个答案:

答案 0 :(得分:0)

您不应该使用num_rows来验证任何内容。这是不可靠和无用的。

在您的情况下,您可以使用fetch()的结果来查看您的查询是否返回任何内容。

if ($stmtRating->fetch()) {
    echo "$valuations <br>
      ...
    ";
    }
} else {
    echo "There are no votes for this product.";
}

请注意,为了控制代码大小,您应该使用PDO而不是mysqli。整个过程将缩短100倍:

$id_product = "1";
$sql = "SELECT SUM(rating IN (4.5, 5))/COUNT(*)*100 AS pct_5_star ...";
$stmtRating = $con->prepare($sql);
$stmtRating->execute([$id_product]);
$rating = $stmtRating->fetch()
if ($rating) {
    foreach ($rating as $value) echo "$value<br>";
} else {
    echo "There are no votes for this product.";
}