Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Rohin Kansal
PLUS
Rohin Kansal
Courses Plus Student 642 Points

Not able to get the number of notifications in php

Hi, I used mysqli_num_rows to get the number of rows of the notifications. But it is showing only one. Can you please figure this out?

Henrik Hansen
Henrik Hansen
23,176 Points

Could you show some code?

An example would be

$result = $mysqli->query("SELECT something FROM table ORDER BY something")
$no_rows = $result->num_rows;

You can read more on [php.net]http://php.net/manual/en/mysqli-result.num-rows.php

3 Answers

Lewis Cowles
Lewis Cowles
74,902 Points

Why not

SELECT COUNT(id) AS 'CNT' FROM `notifications`
<?php
// Using PDO where $conn represents a PDO object
$query = $conn->query("SELECT COUNT(id) AS 'count' FROM `notifications`");
$count = $query->fetch(PDO::FETCH_OBJ);
$count->count;

This should work (it works when counting an arbitrary table with an id primary key)

Sorry it took so long for me to answer, I'm not always active on Forums

Edit: Also always remember to set PDO to errormode exception and use a try, catch block so that you can correctly handle issues.

Henrik Hansen
Henrik Hansen
23,176 Points

Try fetching all results in array.

$all_rows = array();
while ( $row = $result->fetch_assoc() ) {
  $all_rows[] = $row;
}

$no_rows = count($all_rows);

I don't think you'll need a while loop?

<?php

$result = $mysqli->query("SELECT something FROM table ORDER BY something")
$results = $result->fetch_all();
count($results)

Do you have more than one result being returned in the first place?