来自数据库中数据的回声计数

时间:2022-02-01 21:34:01

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],因为它只是获取一个结果。

#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],因为它只是获取一个结果。