简体   繁体   中英

prepared statement count numbers of returning rows

I want to display the total count of users and users being online. However, there are two simple queries for that:

SELECT id FROM users;

and

SELECT id FROM users WHERE online=1;

And this is my code for the first statement

if($stmt = $mysqli->prepare("SELECT id FROM users"))
    {
        $stmt->execute();
        $stmt->fetch();
        $totalcount = $stmt->num_rows;
        $stmt->close();
        $stmt = null;

    }

for the second:

if($stmt = $mysqli->prepare("SELECT id FROM users WHERE online=?"))
    {
        $requ = 1;
        $stmt->bind_param("i", $requ);
        $stmt->execute();
        $stmt->bind_result($onlineUsers);
        $stmt->fetch();
        $count = $stmt->num_rows;
        $stmt->close();
        $stmt = null;

    }

It just returns 0 as total count of users and online users. How can you perform such a check?

Instead of selecting all the rows, do a SELECT COUNT(*) query so that the count is returned as the result. In fact, you can combine the two queries into one:

if ($stmt = $mysqli->prepare("SELECT COUNT(*), SUM(online = ?) FROM users") {
    $requ = 1;
    $stmt->bind_param("i", $requ);
    $stmt->execute();
    $stmt->bind_result($totalcount, $count);
    $stmt->fetch();
    $stmt->close();
    $stmt = null;
}
if($stmt = $mysqli->prepare("SELECT COUNT(id) FROM users WHERE online=?"))



 $requ = 1;
    $stmt->bind_param("i", $requ);
    $stmt->execute();
    $stmt->bind_result($onlineUsers);
    $stmt->fetch();
    echo $onlineUsers;
    $stmt->close();
    $stmt = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM