简体   繁体   中英

How to get number of results from a mysqli query?

So I'm doing this query:

'SELECT * FROM Album WHERE id = ?;'

using a prepare sql statement, and I was wondering how to get the number of results this query returns? B/c since every album id is unique this query should only return 1 album and I want to make sure that its doing that.

Code

$stmt = $mysqli->prepare('SELECT * FROM Album WHERE id = ?;');
$id = 2;
$stmt->bind_param('i', $id);
$executed = $stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
    $info['id'] = $row['id'];
    $info['title'] = $row['title'];
    $info['date_created'] = $row['date_created'];
    $info['creator'] = $row['creator'];
}
// Send back the array as json
echo json_encode($info);

You can get it using $result->num_rows :

if ($row = $result->fetch_assoc()) {
    $info['id'] = $row['id'];
    $info['title'] = $row['title'];
    $info['date_created'] = $row['date_created'];
    $info['creator'] = $row['creator'];

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;
    
    printf("Result set has %d rows.\n", $row_cnt);
}

You can find more details on PHP Documentation .

I want to make sure that its doing that

In your code you are already doing that. The following condition

if($row = $result->fetch_assoc()){

does exactly what you want.

Just use COUNT(*)

SELECT COUNT(*) FROM Album WHERE id = ?;

Reference: https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html

Another way

$query = $dbh->prepare("SELECT * FROM Album WHERE id = ?");
$query->execute();
$count =$query->rowCount();
echo $count;

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