简体   繁体   中英

SQL query doesn't give any results in PHP

I am using the following query:

$query = "SELECT (SELECT count(*) FROM survey_ptw WHERE erfh= '0') AS F01,
                 (SELECT count(*) FROM survey_ptw WHERE erfh='10') AS F02,
                 (SELECT count(*) FROM survey_ptw WHERE erfh='50') AS F03";
$result = mysql_query($query);
print sprintf('Erf: <table><tr><td>none</td><td>%s</td></tr><tr><td>more</td><td>%s</td></tr></table>', $F01,$F02);

When I'm doing the above query in phpMyAdmin, it displays the variables nicely with the correct result values. Doing the same in PHP however, no results are displayed (empty strings)! mysql_errno() and mysql_error() don't return errors. The DB has been open and selected further up in the code.

Any idea what's going on?

Because you aren't doing anything with the results.

From the documentation for mysql_query() :

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

So, to retrieve the results, you can use a while loop as below:

while ($row = mysql_fetch_assoc($result)) {
    # code...
}

check $res=mysql_fetch_assoc($result); then print_r(); to check the result. it will work.

$query = "SELECT (SELECT count(*) FROM survey_ptw WHERE erfh= '0') AS F01,
                 (SELECT count(*) FROM survey_ptw WHERE erfh='10') AS F02,
                 (SELECT count(*) FROM survey_ptw WHERE erfh='50') AS F03";
$result = mysql_query($query);
$res=mysql_fetch_assoc($result);
$res=$res[0];
sprintf('Erf: <table><tr><td>none</td><td>%s</td></tr><tr><td>more</td><td>%s</td></tr></table>', $res['F01'],$res['F02']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM