Bob
Bob

Reputation: 39

MySQL PHP query always returning 1

This script always returns one, not the actual number of online users. Can anyone help fix my code?

$oq = "SELECT user FROM user_archive WHERE time > (NOW() - INTERVAL 5 MINUTE)";
$oresult = mysqli_query($con,$oq);
$online_users = mysqli_num_rows($oresult);

if($online_users = 1)
{
     echo "{$online_users} user online";    
}

if($online_users != 1)
{
echo "{$online_users} users online";    
}

Upvotes: 0

Views: 89

Answers (4)

Daryl Gill
Daryl Gill

Reputation: 5524

Using one equals sign is something called an assignment operator so:

$Var = 1; // This variable equals to 1

But when validating.

if ($Var == 1){

} // Notice the use of two equals, for a comparison operator

http://php.net/manual/en/language.operators.comparison.php

Upvotes: 1

VihG
VihG

Reputation: 11

In the line of code where you wrote:

if($online_users = 1)

You are asigning the value 1 to $online_users, instead of comparing the value. It should be:

if($online_users == 1)

Upvotes: 1

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

You need to use == instead of =

if($online_users == 1)
{
     echo "{$online_users} user online";    
}

Upvotes: 1

CodeAngry
CodeAngry

Reputation: 12985

$online_users = 1 must be $online_users == 1.

And

$oq = "SELECT COUNT(*) FROM user_archive WHERE time > (NOW() - INTERVAL 5 MINUTE)";

or

$oq = "SELECT COUNT(DISTINCT user) FROM user_archive WHERE time > (NOW() - INTERVAL 5 MINUTE)";

COUNT(*) counts, not what you do.

Why retrieve rows of data to counts them when you can just get one integer back and get MySql to count for you?

Upvotes: 0

Related Questions