加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 非常奇怪的数据库查询结果

发布时间:2020-12-13 21:40:20 所属栏目:PHP教程 来源:网络整理
导读:我的数据库查询得到了一个非常奇怪的结果,我希望有人能发现我错过的东西. 我的表中有一些示例数据: feeling_id country date feeling digit25 australia 2011-02-21 bad 126 australia 2011-02-21 bad 08 france 2011-02-21 better 1 我试图计算数据库中每
我的数据库查询得到了一个非常奇怪的结果,我希望有人能发现我错过的东西.

我的表中有一些示例数据:

feeling_id  country     date            feeling     digit
25          australia   2011-02-21      bad         1
26          australia   2011-02-21      bad         0
8            france      2011-02-21      better      1

我试图计算数据库中每个国家的数量,以及其中有多少数字为1.因此上述数据将给出:

澳大利亚,数字为1 = 1

数据库中的澳大利亚行= 2

数字为1 = 1的法国

数据库中的france行= 1

这是代码

<?php

include ('mysqli_connect.php'); // indclude mysql connection functions

$countries = array('united states','canada','united kingdom');
$r = array(); 

foreach($countries as $country){
        //e.g. $r_spain holds the results from the query below with spain as $country
        $r[$country] = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country' AND digit='1'");

        //loop through the results
        while($row = mysqli_fetch_array($r[$country],MYSQLI_ASSOC)){
                $rowCount = mysqli_num_rows($r[$country]);

        }       

        //e.g. $r_spain holds the results from the query below with spain as $country
        $r[$country] = mysqli_query($dbc,"SELECT * FROM feelings WHERE country = '$country'");

        //loop through the results
        while($row = mysqli_fetch_array($r[$country],MYSQLI_ASSOC)){
                $rowCount2 = mysqli_num_rows($r[$country]);

        }   

echo $country . '=' . $rowCount . '<br />';
echo $country . '=' . $rowCount2 . '<br />';

}
?>

当数据库中只有两个加拿大行时,我得到以下结果,这些行都没有数字1 ???

美国的数字为1 = 13

数据库中的美国行= 17

数字为1 = 13的加拿大

数据库中的加拿大行= 2

联合王国,数字为1 = 4

数据库中的联合王国行= 4

答案应该说:“数字为1 = 0的加拿大”

1答案的数字加拿大似乎复制了1个结果的美国数字.

任何人都可以看到我哪里出错了?

非常感谢,alsweeet

解决方法

您需要在foreach的开头将$rowCount和$rowCount2设置为0.因为没有找到加拿大的行,所以它永远不会进入while循环,因此使用上一次迭代中$rowCount和$rowCount2的值.

foreach($countries as $country){
    $rowCount = 0;
    $rowCount2 = 0;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读