eozzy
eozzy

Reputation: 68670

Geting total row count in MySQL

$rowCount = $conn->query('SELECT COUNT(*) FROM Users');
echo '<pre>'.print_r($rowCount,1).'</pre>';

returns:

mysqli_result Object
(
    [current_field] => 0
    [field_count] => 1
    [lengths] => 
    [num_rows] => 1
    [type] => 0
)

... although the table has 978 rows as I see in PHPMyAdmin.

Upvotes: 3

Views: 139

Answers (2)

nomistic
nomistic

Reputation: 2962

You are using print_r to generate the number of rows in your query. Your query is only returning one row, which is the count of rows.

Try this:

$rowCount = $conn->query('SELECT COUNT(*) as rowNumber FROM Users');
$row = $rowCount->fetch_assoc();
echo $row['rowNumber'];

Upvotes: 7

Chico3001
Chico3001

Reputation: 1963

query returns an object, you need to fetch the result from that object

$sql = "SELECT COUNT(*) AS count FROM Users";

if ($res = $mysqli->query($sql)) {
    /* Fetch object array */
    while ($obj = $res->fetch_object()) {
        echo '<pre>'.print_r($obj->count,1).'</pre>';
    }
    $res->close();
}

Upvotes: -1

Related Questions