Reputation: 42496
I'm trying to get all of the values in a certain field in a table. The basic query:
SELECT `field`
FROM `table`
WHERE `category`="something"
ORDER BY `other_field` DESC
The names of these fields will be return to an AJAX call, so my idea right now is to get this information into an array, and then json_encode
that array.
But it's just a list of names, and it's ending up in JavaScript. And my "array/encode" method would require going over the results twice (when the query returns, I'd have to convert a two-dimensional array to one-dimensional). I'd like to avoid that, if possible.
So is there a better method to do this that I don't see? Is there MySQL function that will return all the field
s as a single array?
Upvotes: 2
Views: 876
Reputation: 37364
You can try to use GROUP_CONCAT
to get all field
values in one row, then convert it to array by explode
in php. I'm not sure if it is faster than iterating over collection though.
Update A short query example.
SELECT GROUP_CONCAT(`field` ORDER BY `order_field` DESC SEPARATOR '|')
FROM `table`
WHERE `category`="something";
*Notice : while choosing separator, make sure it doesn't occur in field
's values. It's also possible to escape occurrences of separator in field
using, for instance, REPLACE
Upvotes: 3