PHP计算数据库中特定条目的行数

时间:2014-03-12 04:30:18

标签: php mysql

PHP的新手,并为类似问题的所有不同解决方案所淹没。我不知道我是否有编码问题,多个查询问题,或两者都有。

在一个php文件中,我打开一个连接,运行一个查询,然后成功计算该条目出现在数据库中的次数......或至少尝试。

// $team1, $team2 and $page come in through _POST up here...

$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

// build long query at this point...

$result = mysqli_query($connection, $query);

//I was successful getting it into the database, now I want to count how many times each entry appears.
if ($result) {
        $team1result = mysqli_query($connection,"SELECT * FROM {$page} WHERE 'vote' = {$team1}") ;
        $team1row = mysqli_fetch_row($team1result);
        $team1count = $team1row[0];

        $team2result = mysqli_query($connection,"SELECT * FROM {$page} WHERE 'vote' = {$team2}") ;
        $team2row = mysqli_fetch_row($team2result);
        $team2count = $team2row[0];

        echo $team1count . " and " . $team2count;
}

我能够很好地插入到数据库中,然后我的console.log会亮起......

警告:mysqli_fetch_row()期望参数1为mysqli_result,boolean在...中给出
警告:mysqli_fetch_row()要求参数1为mysqli_result,布尔值为...

感谢今晚的所有帮助。

解决方案(感谢愿望):

if ($result) {
    $team1rows = mysqli_num_rows(mysqli_query($connection,"SELECT * FROM $page WHERE vote = '$team1'"));
    $team2rows = mysqli_num_rows(mysqli_query($connection,"SELECT * FROM $page WHERE vote = '$team2'"));
    echo $team1 . " : " . $team1rows . "   |   ". $team2 . " : ". $team2rows;
}

2 个答案:

答案 0 :(得分:1)

查询$ team1result和$ team2result没有结果行。这就是你得到这个错误的原因。

使用if语句来检查

if($team1result)
$team1row = mysqli_fetch_row($team1result);

if($team2result)
$team2row = mysqli_fetch_row($team1result);

你不会得到错误。

要计算查询结果的行数,请使用下面的

$rows=mysqli_num_rows(mysqli_query($query));    

并且在查询语句中找到错误的好习惯就是回应它。

在这种情况下

echo "SELECT * FROM $page WHERE vote = '$team1'";
echo "SELECT * FROM $page WHERE vote = '$team2'";

检查回显的查询是否没有错误(如未定义的变量)。

答案 1 :(得分:0)

您可以使用num_rows轻松统计这一点,无需访问其索引和所有内容,只需使用此

即可
echo $team1row = mysqli_num_rows($team1result);

Reference Link