user1481563
user1481563

Reputation: 125

Returning an array of column data MySQL/PHP

I know there is mysql_fetch_assoc which puts all data from a row into an array. Is there something equivalent for putting all data in a column into an array? e.g. a list of title ID's?

Upvotes: 0

Views: 74

Answers (3)

Chris Henry
Chris Henry

Reputation: 12010

If you're able to use external libraries, it may be worth looking into the Zend database library. Zend_Db provides a function called fetchCol where it will return an array without having to write any additional code.

Upvotes: 0

John Conde
John Conde

Reputation: 219924

GROUP_CONCAT and explode() is probably what you're looking for as it can get everything in one row. You can group all of the values with a comma using GROUP_CONCAT and then populate the array using explode().

Your SQL would contain this:

SELECT GROUP_CONCAT(column_name SEPARATOR ',') AS col

And your PHP would create the array like this (after performing the query):

$col_array = explode(',' $row['col']);

Upvotes: 1

Ruel
Ruel

Reputation: 15780

Here's my suggestion:

$arr = array();
while ($row = mysql_fetch_assoc($result)) {
  $arr[] = $row['id']; // replace id with your column name.
}

var_dump($arr);

Upvotes: 0

Related Questions