Skip to content
Advertisement

Get Count For A Set Of Fetched Field Values – MySQL / PHP

I have some data returned from a MySQL database that outputs the post details for a particular user.

I’d like to output a count for the number of images (represented below by the $db_image_filename value).

How do I get a count for the number of field values in a column? I thought I could use PHP’s count() function, but this didn’t work?

Is there a way to do this in PHP without running another query on the database (seeing as this data has already been fetched from the database, and I just need its count value)? This value will then be echoed out in the <p> tag at the bottom of the example below.

JavaScript

Advertisement

Answer

Define a variable $count_images = 0 before your while loop and inside the loop increase the variable by +1 every time there is a $row['filename'] which is not NULL or an empty string.

After the while loop you can echo $count_images:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement