简体   繁体   中英

MYSQL returns empty result in PHP

I have the following tableCountry

country  clicks
-------  ------
0        222
66       34 
175      1000
45       650

And I use the following MYSQL statement to get the ranking of any of the country based on the clicks column (just one result)

SELECT COUNT(*) rank 
FROM countryTable a 
JOIN countryTable b 
   ON a.clicks <= b.clicks 
WHERE a.country = 45

The above will return '2'. Then in my php code I try to access the rank value with

$row =  mysql_fetch_array($result) or die(mysql_error()); 
echo $row['rank'];

But this doesn't return any result if the country is the number one. ie a.country = 175

A join ON is a join between columns, not a comparison.

UPDATED

SELECT COUNT(*)+1 rank 
FROM countryTable
WHERE clicks > (SELECT clicks FROM countryTable WHERE country = 45)

Reasoning: searching for a rank mean searching for the number of records that has clicks > a given click.

Therefore, for 175 there is 0 country with better click => rank 1, country 45, 1 country with better click => rank 2

PHP

$result = mysql_query("....")
$row = mysql_fetch_array($result)
...

Normally it should work unless you got a problem with connecting to the server. That's where you should use your debugging skill. Do a var_dump($result) to see if it return false, if yes then it's a connection problem (check mysql_connect or something)

If you're looking for ranking, use this:

SELECT @rownum := @rownum + 1 AS num,
    t.country, t.clicks
FROM countryTable t, 
    (SELECT @rownum := 0) r
ORDER BY t.clicks DESC

Result

| NUM | COUNTRY | CLICKS |
--------------------------
|   1 |     175 |   1000 |
|   2 |      45 |    650 |
|   3 |       0 |    222 |
|   4 |      66 |     34 |

See it in action

@PutraKg我想你可以关闭这个问题,因为我在这篇文章中回答了它, 当被问到第一个排名时,MYSQL没有返回PHP的结果 ;-)

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