1

I am trying to count the number of records I have in a certain. This is the SQL query I have been using and I have tried to echo $result, but nothing would print.

$result = $mysqli->query("SELECT COUNT(*) FROM barber_queue ");
echo $result;

I have also tried this code which managed to return something, however not in the format I would like

$result = $mysqli->query("SELECT COUNT(*) FROM barber_queue ");
$row = mysqli_fetch_row($result);
print_r($row);

This returns:Array ( [0] => 6 ) While 6 is the correct amount of rows, I would just like the integer on its own as I want to use this amongst HTML to relay some information back to visitors.

Also this piece of code

$result = $mysqli->query("SELECT COUNT(*) FROM barber_queue ");
    print_r($result);

returns on the screen. :

mysqli_result Object ( )

Any Help is appreciated.

1
  • $rowcount=mysqli_num_rows($result);// try this Commented Apr 12, 2015 at 16:56

2 Answers 2

1

I added an alias "num" to the COUNT() keyword, the accessed the $row variable as an array();

$result = $mysqli->query("SELECT COUNT(*) num FROM barber_queue ");
$row = mysqli_fetch_assoc($result);
echo $row['num'];
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect, worked wonders, but Im sure Ive seen somewhere that you can just print count directly from the result of the query?
No you can't. The query returns a resource. You need to fetch the result from that resource.
You can execute queries returning no result ... ex: $mysqli->query("insert into table .....") ... then you get the inserted id by calling extra function mysql_insert_id ... but if you want to get a rowset you have to fetch it first by calling mysqli_fetch_row($query)
0

you are missed mysqli_fetch_row(...);. you are dumping the system mysql_query object, which can not be access by print_r so you have this dump

2 Comments

Im sure I used fetch row in the middle example
of course, that's why you have result there ... if you want to count result rows mysqli_num_rows is the function you should use ... if you want to substitude the name of the field ... the clean SQl syntax is field as newfieldname - in your case count(*) as count for example ... but you need to fetch your result first. The $mysqli->query won't start fetching the result and because it is low level object it can not be dumpped successfuly by print_r or var_dump

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.