Resource ID#5 PHP MySQL Error

2019-08-30 23:37发布

问题:

I have this code:

<?php

$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
     if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

     mysql_select_db(DB_NAME, $con);

 $result = mysql_query("SELECT SUM(colname) FROM profits");

 $total = reset (mysql_fetch_assoc($result));

 mysql_close($con);

 echo $total;

 ?>

And its outputting an Resource id #5. Any help? Thanks in advance!

回答1:

Don't use reset() like that - if you need a single value, just use list():

$result = mysql_query("SELECT SUM(colname) FROM profits");
list($total) = mysql_fetch_array($result);

reset() does not work as you expect on associative arrays: https://bugs.php.net/bug.php?id=38478



回答2:

You're trying to echo an associative array with echo $total;. Instead just echo the first (and probably only based on your query) item.

$row = mysql_fetch_assoc($result);
echo $row[0];


标签: php mysql sum