Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the result of a select count(*) query in PHP?

Tags:

php

mysql

I have this query to use in PHP:

mysql_query("select count(*) from registeredUsers where email=".$_SESSION["username"]);

When I use echo to print out the result, nothing gets printed. What exactly is the return value from the above statement?

like image 299
user722769 Avatar asked Apr 22 '11 17:04

user722769


People also ask

What is the result of given query SELECT count (*)?

SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list.

How can I get SQL query results in PHP?

Show activity on this post. require_once('db. php'); $sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1" $result = mysql_query($sql); echo [$result]; and here is what i get.

How does count (*) work in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


3 Answers

Your code doesn't include any fetch statement. And as another answer notes, you need single quotes around $_SESSION["username"].

$result = mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'");

// Verify it worked
if (!$result) echo mysql_error();

$row = mysql_fetch_row($result);

// Should show you an integer result.
print_r($row);
like image 110
Michael Berkowski Avatar answered Oct 07 '22 18:10

Michael Berkowski


mysql_query returns a result resource. You can read the result with mysql_result

$res = mysql_query("select count(*) from registeredUsers where email='".mysql_real_escape_string($_SESSION["username"])."'");
echo mysql_result($res,0);
like image 33
Frank Farmer Avatar answered Oct 07 '22 18:10

Frank Farmer


You need single quotes around the session variable in your query

$result = mysql_query("SELECT COUNT(*) 
                       FROM registeredUsers 
                       WHERE email = '".$_SESSION['username']."' ");
like image 24
Brett Avatar answered Oct 07 '22 18:10

Brett