Adam Hamilton Adam Hamilton - 6 months ago 154
MySQL Question

Mysqli num_rows( ) returning undefined property

I'm trying to count up the amount of registered users in my database however, I am having a problem with the num_rows.. as its giving an error.

Here is my index.php code:

<?php
require 'connections.php';
$con->query("SELECT users, UserID from users");
$totalplayers = $con->num_rows;
?>


Here is my connections.php:

<?php
ob_start();
session_start();
$con = mysqli_connect("localhost", "root", "", "website");

if (isset($_SESSION['UserID'])) {
$result = $con->query("select * from users where UserID=".$_SESSION['UserID']);
$row = $result->fetch_assoc();


However, it is giving this error and I have no clue what to do!:


Notice: Undefined property: mysqli::$num_rows in C:....\index.php
on line 4

Answer

you should assign the result of the query and then get the count :

<?php
require 'connections.php';
$result = $con->query("SELECT users, UserID from users");
// $result is a mysqli_stmt
$totalplayers = $result->num_rows;
?>

Reference: http://php.net/manual/en/mysqli-stmt.num-rows.php