嗨,我已经阅读了其他答案,但是似乎无法使它对我有用。

我正在创建一个新表,但是如果没有行,我想将0放入变量中

我下面的代码返回如下表:

 was_recalled  | total


它有空行。

我想在这种情况下发生的就是这样

was_recalled    | total
Yes             |   0


这是我的代码:

<?php
    $barPrelimSql = "select was_recalled, count(*) as total FROM mark_cards1 WHERE school = '$ownerSchool' AND was_recalled = 'Yes' AND competition_level1 = 'Prelim Champion' GROUP BY was_recalled";
    $barPrelimRes = mysqli_query($con,$barPrelimSql);

    while ($barPrelimRow=mysqli_fetch_array($barPrelimRes)){
        $barPrelimR = $barPrelimRow["total"];



        ?>

  var dataLace = google.visualization.arrayToDataTable([
      ['Placement', 'Recalled', 'Not Recalled'],
      ['Prelim Champs', <?php echo $barPrelimR; ?>, 5],
      ['Open Champs', 5, 24],
      ['Majors', 54, 44],

  ]);

        <?php } ?>

最佳答案

您在查询中使用按条件分组,这是当查询中没有行时它将不返回0计数的原因。

在我的建议中,您可以检查查询返回的行数是否为零,然后可以直接将其设置为0。

<?php
$barPrelimSql = "select was_recalled, count(*) as total FROM mark_cards1 WHERE school = '$ownerSchool' AND was_recalled = 'Yes' AND competition_level1 = 'Prelim Champion' GROUP BY was_recalled";
$barPrelimRes = mysqli_query($con,$barPrelimSql);
$row_count = mysqli_num_rows($barPrelimRes);
if($row_count > 0){
    while ($barPrelimRow=mysqli_fetch_array($barPrelimRes)){
        $barPrelimR = $barPrelimRow["total"];
        var dataLace = google.visualization.arrayToDataTable([
              ['Placement', 'Recalled', 'Not Recalled'],
              ['Prelim Champs', $barPrelimR, 5],
              ['Open Champs', 5, 24],
              ['Majors', 54, 44],

        ]);
    }
}
else{
    $barPrelimR = 0;
    var dataLace = google.visualization.arrayToDataTable([
          ['Placement', 'Recalled', 'Not Recalled'],
          ['Prelim Champs', $barPrelimR, 5],
          ['Open Champs', 5, 24],
          ['Majors', 54, 44],

    ]);
}


?>

关于php - 如果数据库PHP中没有行,如何返回零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57009246/

10-12 12:52
查看更多