來自數據庫中數據的回聲計數

[英]Echo count from data in a database


I am trying to count a specific field in a database that has user details in it. Every user has an id and I want to count the amount of users/ids that are registered in the database. This is my code, how can I solve it? Because it does not echo anything. I am not allowed to use MYSQL to retrieve the count.

我正在嘗試計算數據庫中具有用戶詳細信息的特定字段。每個用戶都有一個id,我想計算在數據庫中注冊的用戶/ ID數量。這是我的代碼,我該如何解決?因為它沒有回應任何東西。我不允許使用MYSQL來檢索計數。

include ("databaseconnectie.php");
$query = $db->prepare("
    SELECT 
        COUNT(id) as total 
    FROM 
        users");

$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);

echo $result['total'];`

1 个解决方案

#1


2  

Due to the way you fetch'ed your data, you will need to add [0] in the $result echo. ($result[0]['total']).

由於您獲取數據的方式,您需要在$ result echo中添加[0]。 ($結果[0] [ '總'])。

I added in a print_r($result) to show me the array so I could identify where the issue came from and how I can step through the array to get my intended result.

我添加了一個print_r($ result)來向我展示數組,這樣我就可以確定問題的來源以及如何逐步完成數組以獲得我想要的結果。

$query = $db->prepare("SELECT COUNT(id) as total FROM users");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
echo $result[0]['total'];

EDIT:

As mentioned by @Federkun; you could change this line:

如@Federkun所述;你可以改變這一行:

$result = $query->fetchAll(PDO::FETCH_ASSOC);

$ result = $ query-> fetchAll(PDO :: FETCH_ASSOC);

to:

$result = $query->fetch(PDO::FETCH_ASSOC);

$ result = $ query-> fetch(PDO :: FETCH_ASSOC);

Then you wouldn't need to add the [0] as it is just fetching one result.

然后你不需要添加[0],因為它只是獲取一個結果。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/05/29/724da16bba16f3b94c3c1a15b7131a51.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com