gpt4 book ai didi

php - 如果数据库中不存在行如何返回零 PHP

转载 作者:行者123 更新时间:2023-11-29 15:46:16 26 4
gpt4 key购买 nike

您好,我已经阅读了有关此问题的其他答案,但似乎无法让它为我工作。

我正在创建一个新表,但如果不存在行,我想将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com