查询后从PHP/MySQL中的数据库行返回值0

查询后从PHP/MySQL中的数据库行返回值0

问题描述:

我正在尝试创建一个页面,我可以在其中获取数据库的记录值.我的查询是这样的:

I am trying to create a page where I can get the record values of a Database. My query is like this:

因此,我需要从表示例中获取状态值1(作为计数)的数量(如果存在)并对其进行计数,如果不存在,则需要从中获取值为0.要获取值,我使用此代码,它可以很好地工作,但是如果未找到结果,我似乎无法在我的PHP代码上使该值返回0.我有点迷茫.

So I need to get the number of the values 1 on status (as count) from the tableexample if they exist and count them, if they do not exist, I need to get the value as 0 from it. To get the values I use this code and it works great, but I cannot seem to have the value return 0 on my PHP code if no results are found. I am a bit lost.

$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'";
$request = mysqli_query($systems, $query);
if (mysqli_num_rows($request) > 0) {
    while ($row = mysqli_fetch_array($request)) {
        echo '' . $row["value_sum"] . '';
    }
} else {
    echo '0';
}

所以这段代码可以毫无问题地获取值,但是当我放置"else"时,它应该给我值0,但是却什么也没给我.

So this code gets the values without any issue, but when I place "else" it should give me value 0 but does not give me anything.

有什么想法可以解决这个问题,而又无需更改代码太多?

Any idea on how I can solve this without changing my code so far as much?

使用PDO会像这样:

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";

$pdo = new PDO($dsn, "username", "password", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$stmt = $pdo->prepare('
    SELECT SUM(count)
    FROM `table_example` 
    WHERE `user` = :user 
    AND `status` = "1"'
);

$stmt->bindParam(':user', $_SESSION["user"], PDO::PARAM_STR);
$stmt->execute();
$sum = $stmt->fetchColumn();
echo $sum;

您无需编写任何循环或先前的检查即可获取SUM值.

You don't need to write any loop or previous check in order to get the SUM value.