Reading only one column from SQL output as a numerical array in PHP
I run the following query:
SELECT tagID,
COUNT(*) AS TotalOccurrences
FROM coupon_tags
GROUP BY tagID
ORDER BY TotalOccurrences DESC
LIMIT 10
It returns output like this:
tagID TotalOccurrences
------------------------
7 9
2 8
1 3
6 2
3 1
4 1
5 1
8 1
I can'开发者_JAVA百科t do a mysql_fetch_array(mysql_query($thatQuery);
because it has two columns of data and any array pulled looks like garbage. How can I further streamline that query to a single column of still-sorted data, so it's easier to work with in an array? Or maybe I am using the wrong PHP/MySQL function (although I looked through them all)?
Edit: I've found out that the query will work fine in phpMyAdmin but it fails when I try to query with mysql_query()
.
My php code:
$tagSQL = mysql_query($selectorSQL);
if (!$tagSQL) die("query failed"); //fails here
while ($tSrow = mysql_fetch_assoc($tagSQL)) {
var_dump($tSrow);
}
You can do it like this to "streamline that query to a single column of still-sorted data".
SELECT tagID
FROM coupon_tags
GROUP BY tagID
ORDER BY COUNT(tagID) DESC
LIMIT 10
Just make sure to use count on a single column instead of counting everything, this will greatly affect performance.
Don't try and do everything in one line. Makes it hard to debug.
$sql = "SELECT ...";
$result = mysql_query($sql);
if (!$result) die("query failed");
while ($row = mysql_fetch_assoc($result)) {
var_dump($row);
}
精彩评论