简体   繁体   中英

Count registered users in database

I would like to echo the number of people registered on my website only the code that I have does not work, it gives me back that it can't be converted to string. Also when I make it a function to call in my HTML I get error that $connection is undefined

require_once("connect.php");

$sql = "SELECT * FROM persons";
if ($result=mysqli_query($connection, $sql)){
$rowcount = mysqli_num_rows($result);
mysqli_free_result($result);
return $result;}

How do I get this in a function that I can call on my page that prints the number of people registered?

First of all you should use count because of speed issues:

$sql = "SELECT COUNT(id) FROM persons";

To write a function that returns the number, you can do something like

function registredMemberCount ($connection) 
{
    $sql = "SELECT COUNT(id) FROM persons";
    $result = mysqli_query($connection,$sql);
    $rows = mysqli_fetch_row($result);
    return $rows[0];
}

and call it with

registredMemberCount($connection);
require_once("connect.php");

function blah()
{
    global $connection;
    $sql = "SELECT COUNT(*) FROM persons";
    if ($result=mysqli_query($connection, $sql)){
        $row= mysqli_fetch_array($result);
        $rowcount = $row[0];
        mysqli_free_result($result);
    }
    return $rowcount;
}

echo blah();

Lets see this,

require('connect.php');
function total_num_users(){
  $sql = "SELECT * FROM persons";
  $result = mysqli_query($connection,$sql);
  $count = mysqli_num_rows($result);
  return $count; 
}

And you can call and echo it like this.

echo total_num_users();

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