Best comparison operator when using COUNT in mysqli query

Go To StackoverFlow.com

1

Doing a mysqli query and COUNTing the results, is there a preferred comparison operator & string enquoting to use?

For example

$query = mysqli_query($connect, "SELECT COUNT(`user_id`) FROM `users` WHERE `user_color` = '{$color}'");
$result = mysqli_fetch_assoc($query);
if ($result['COUNT(`user_id`)'] != 0){
 -- then do something....

My question is, what are the implications of using:

if ($result['COUNT(`user_id`)'] != '0'){

versus

if ($result['COUNT(`user_id`)'] != 0){
2012-04-04 03:26
by MadDogDean


0

Both are same, php takes care of string and number.

Internally functionality of php interpreter: If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

2012-04-04 03:33
by Madan
Thanks, that's what I thought, a little confirmation always makes your code feel warm & fuzzy.. - MadDogDean 2012-04-04 03:36


1

My preference would be:

... "SELECT COUNT(`user_id`) as user_count ..." ...

if ($result['user_count'])

0 and '0' are both false in PHP, so this does what you're looking for very concisely.

2012-04-04 03:32
by deceze
I knew about the False value, just never thought of using it in this sense. Actually I just grabbed this chuck of code, several others I use actually compare to something. Thanks - MadDogDean 2012-04-04 03:39


0

Have a look at: Comparison Operators

<?php

0=='0'; // true
0==='0' // false

0!='0'; // false
0!=='0'; // true

?>

in your case it doesn't matter since you are only using one =

2012-04-04 03:38
by stewe
thanks. But I think deceze and Madan caught the drift of what I was thinking. It was more a what does $result['COUNT(user_id)'] prefer to compare to - MadDogDean 2012-04-04 03:46


0

use mysqli_fetch_row instead of mysqli_fetch_assoc.

$result = mysqli_fetch_row($query);
if ($result[0] != 0){
    // your code
}
2012-04-04 05:05
by MajidTaheri
Ads