1

I am trying to count the number of rows in a table, using the count function. I currently have 5 rows in the table in question. However the count function is only counting 1 row. Why is this? Any suggestions.

 $count_pcode = mysqli_query($dbc, "SELECT COUNT(*)FROM Delivery_Pcode");
 $count_row =mysqli_num_rows($count_pcode);
 printf("%d results.\n",$count_row);
 mysqli_free_result($count_pcode );
 mysqli_close($dbc);
2
  • 6
    Only one row is returned when you do a count; the value returned in that row contain the count value Commented May 22, 2016 at 23:17
  • Possible duplicate of count and fetch rows in php Commented May 22, 2016 at 23:19

3 Answers 3

2

Just change the first line to:

$count_pcode = mysqli_query($dbc, "SELECT * FROM Delivery_Pcode");

The next line of code will then tell you how many rows your query return

$count_row =mysqli_num_rows($count_pcode);
Sign up to request clarification or add additional context in comments.

3 Comments

Damn, you bet me by 20s xD
Brilliant. Let's return the entire table from MySQL to PHP, potentially consuming considerable CPU, RAM and network bandwidth—solely in order to obtain a simple integer. Fantastic work! Well done.
If you leave the original query as is, you could change the next line to $count_row = $count_pcode->fetch_row()[0]; and get the result you want without returning the entire recordset worth of data.
2

This code should count the number of rows, and do so efficiently.

$result = mysql_query($dbc, "SELECT COUNT(*)FROM Delivery_Pcode");

// Verify it worked
if (!$result) echo mysql_error();

$row = mysql_fetch_row($result);

// Should show you an integer result.
print_r($row);

mysqli_free_result($result);
mysqli_close($dbc);

Comments

1

Try the following:

$count_pcode = mysqli_query($dbc, "SELECT * FROM Delivery_Pcode");
$count_row = mysqli_num_rows($count_pcode);

3 Comments

Brilliant. Let's return the entire table from MySQL to PHP, potentially consuming considerable CPU, RAM and network bandwidth—solely in order to obtain a simple integer. Fantastic work! Well done.
@eggyal calm down, lad. We're both just giving him the answer he wanted.
@Blue no problem! Happy to help! :)

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.