简体   繁体   中英

Using php to count rows in mysql database?

I am trying to count all rows from demos table but i got an error
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\\xampp\\htdocs\\working_scripts\\test_2.php on line 8
My php code is:

<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo"Error connecting to database". mysqli_connect_error();
}
$comment_counter=mysqli_query($con,"SELECT COUNT(*) AS total FROM demos");
echo $comment_counter;
?>

You have to use mysqli_fetch_array

<?php
$con = mysqli_connect("localhost","root","","test");

if (mysqli_connect_errno())
{
    echo"Error connecting to database". mysqli_connect_error();
}

$result = mysqli_query($con, "SELECT COUNT(*) AS total FROM demos");

if($row = mysqli_fetch_array($result))
{
    echo $row["total"];
}
?>

Try this ->

<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
    echo"Error connecting to database". mysqli_connect_error();
}

$result = mysqli_query($con, 'SELECT COUNT(*) as total FROM demos');
if($row = mysqli_fetch_array($result))
    echo $row["total"];
?>

OR

$result =  mysqli_num_rows(mysqli_query($con, 'SELECT * FROM demos'));
echo $result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM