Answer the question
In order to leave comments, you need to log in
How to display using PHP - the number of records from the SQL table (base) on the html page?
Dear experts!
I ran into a problem - where I did not expect it at all ..
I need to use PHP to display the number of records from a SQL table (base) on an html page.
I thought it was a trifling matter, but I have been fighting for the 2nd day, and all to no avail ..
What I did and how I reasoned:
First of all, I wrote an SQL query and checked its performance directly in the SQL DBMS:
Here it is:
SELECT COUNT(*) FROM `items_table` WHERE id_category = '1'
<i>function get_count_items($id_category){
global $connect_sql;
$sql = "SELECT COUNT(*) FROM `my_php_blog`.`items_table` WHERE id_category = $id_category";
$result = mysqli_query($connect_sql, $sql);
$count_items_return = mysqli_fetch_all($result, 1);
return $count_items_return;
}</i>
<?php $id_count_category = 1; ?> // задаю id-нужной категории
<?php $count_items_return = get_count_items($id_count_category); ?>//вызываю функцию с параметром id-категории
<i><h4> <?php echo $count_items_return; ?> записей</h4></i>
<i><h4> <?php echo $count_items_return[0]; ?> записей</h4></i>
<i><h4> <?php $count_items_return; ?> записей</h4></i>
<i><h4><?php var_dump($count_items_return); ?> записей</h4></i>
array(1)
{ [0]=>
array(1)
{ ["COUNT(*)"]=>
string(1)
"5" }} записей
function get_count_items($id_category){
global $connect_sql;
$sql = "SELECT COUNT(*) FROM `my_php_blog`.`items_table` WHERE id_category = $id_category";
$result = mysqli_query($connect_sql, $sql);
$count_items_return = mysqli_fetch_all($result, 1);
return <b>$count_items_return[0];</b>
}
Answer the question
In order to leave comments, you need to log in
Try doing AS `count_items`
$sql = "SELECT COUNT(*) AS `count_items` FROM `my_php_blog`.`items_table` WHERE id_category = $id_category";
Then your output will be somewhat different and you can take the value more beautifully
echo $count_items_return[0]['count_items'];
But it seems to me that it would be more elegant to do it through fetch_assoc ();
Good luck.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question