I simply want to use PHP to get a count of the total number of rows in a MySQL table, and store the number in a variable called $count
.
I prefer procedural code since my mind doesn't work in object-oriented fashion.
$sql="SELECT COUNT(*) FROM news";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_assoc($result);
echo $count;
The above is the latest I tried. Instead of giving me a number, it gives me the word "Array".
You have a couple of options how to get the value of
COUNT(*)
from the SQL. The easiest three are probably this:or using column alias:
or using numerical array:
Do not use
mysqli_num_rows
to count the records in the database as suggested in some places on the web. This function has very little use, and counting records is definitely not one of them. Usingmysqli_num_rows
you would be asking MySQL to retrieve all matching records from database, which could be very resource consuming. It is much better to delegate the job of counting records to MySQL and then just get the returned value in PHP as shown in my answer.I would also recommend to learn OOP, which makes your code cleaner and easier to read. The same with OOP could be done as follows:
If your query uses variables, then you could do a similar thing, but using prepared statements.
The following PHP can be used to execute the query to calculate the amount of results:
It's better to use COUNT(*) instead of selecting all rows and using
mysqli_num_rows()
.Your basic idea was correct, you just needed to fetch the result properly.