1

Possible Duplicate:
Why does this return Resource id #2?

I want to echo mysql_query("SELECT SUM(onlineplayers) FROM servers") but when I place echo in front, it says Resource Id #2 and when I add or die(mysql_error()); at the end, it just outputs 1.

Community
  • 1
  • 1
Harry
  • 3,301
  • 7
  • 27
  • 33
  • http://stackoverflow.com/questions/4794927/why-does-this-return-resource-id-2 – sgeddes Feb 02 '13 at 06:34
  • WHAT? what do you mean with *when I place echo in front*? – Tomas Ramirez Sarduy Feb 02 '13 at 06:35
  • The return type of `mysql_query()` is not a string result of your query, it is a [resource](http://www.php.net/manual/en/language.types.resource.php) (in your case at least). [Read the docs](http://php.net/manual/en/function.mysql-query.php). – ajp15243 Feb 02 '13 at 06:38
  • the mysql_query() executes the query and returns the output, hence you are getting the output has Resource #2. to output the query you need to assign the query to a variable and echo the variable and pass it to the mysql_query function – Manigandan Arjunan Feb 02 '13 at 06:39
  • 1
    1) Yogesh Suthar is correct. To echo your query string, put it in a variable and echo the variable. 2) You should really be using mysqli or PDO instead of the (old, deprecated) "mysql_query()" API. 3) You should also use prepared statements whenever possible. *MOST IMPORTANT* - 4) you can't just "echo the results of a query". You need to call an API to *fetch* the results. Then you can display what you fetch :) – paulsm4 Feb 02 '13 at 06:40

4 Answers4

2

You need to fetch the query first:

$result = mysql_query("SELECT SUM(onlineplayers) FROM servers");
if($result){
  $data = mysql_fetch_assoc($result);
  echo $data[0];
}

However, you shouldn't use the mysql_ functions unless absolutely necessary. the mysql extension is NOT recommended for use in new projects. Instead you should use PDO_mysql or mysqli

Source: Why does this return Resource id #2?

Community
  • 1
  • 1
Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85
1

use this below code

$str = "SELECT SUM(onlineplayers) FROM servers";  //this will set the query in string format
echo $str;    // this will echo the query;
mysql_query($str);   // this will run the query
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
1
$q = mysql_query("SELECT SUM(onlineplayers) as `total` FROM servers"); // notice the "as `total`
$r = mysql_fetch_array($q); // will return the result
echo $r['total']; // will echo the count

On a sidenote, please stop using mysql_* functions. More info here

Community
  • 1
  • 1
asprin
  • 9,579
  • 12
  • 66
  • 119
0
$str = "SELECT SUM(onlineplayers) FROM servers"; 
echo $str; 
$result = mysql_query($str); 
$row= mysql_fetch_array($result);
print_r($row);
Manigandan Arjunan
  • 2,260
  • 1
  • 25
  • 42