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

标签 php mysqli

我从我的数据库查询中得到一个非常奇怪的结果,我希望有人能发现我错过的东西。

这是我的表格,其中包含一些示例数据:

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 />';

}
?>

当数据库中只有两个 canada 行时,我得到以下结果,这些行的数字都不是 1???

美国数字为 1 =13

数据库中的美国行数 =17

加拿大的数字为 1 =13

数据库中的加拿大行数 =2

英国的数字为 1 =4

数据库中的英国行数 =4


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

数字为 1 的加拿大似乎复制了美国数字的 1 结果。

谁能看出我哪里出错了?

非常感谢,谢谢

最佳答案

当你可以在 sql 上执行 count() 时,为什么要循环遍历结果??

SELECT COUNT(feeling_id) FROM feelings WHERE country = '$country' AND digit='1'

关于php - 非常奇怪的数据库查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5068993/

相关文章:

php - 与数据库phpmyadmin的接口(interface)

php - 在php中从数据库中提取数组

javascript - 下拉列表值不存储在数据库中

PHP MYSQL 插入数据时出错

php - atom.io Laravel 自动预测问题

php - Magento 1.5.1 升级到 1.9.1 现在无法将商品添加到购物车

php - 使用 dropzone.js 和 laravel 5 验证CsrfToken

php - 内存不足,Mysql_query() 无法保存结果集

php - 如何为所有人设置默认时区?

php - 无法使用 php 将值插入 mysql