簡體   English   中英

PHP計算數據庫中特定條目的行

[英]PHP count rows of specific entries in database

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,布爾值在...中給出
警告 :mysqli_fetch_row()期望參數1為mysqli_result,布爾值在...

感謝您今晚的所有幫助。

解決方案(感謝wishchaser):

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;
}

查詢$ 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'";

檢查回顯的查詢是否沒有錯誤(例如未定義的變量)。

您可以使用num_rows輕松計數,無需訪問其索引,只需使用此即可

echo $team1row = mysqli_num_rows($team1result);

參考鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM