Kevin
Kevin

Reputation: 3730

PHP fetch MySQL array with an index

When fetching an array from MySQL the rows are typically returned with a key from 0 to the size of your recordset:

row[0][key][value]

Is it possible to have one of the fields from the select statement returned as the key in the array?

For example. Assuming my data set has StudentID, Name, City, etc.

How can I select into an array where I could refer to the StudentID as the index like this:

rows[StudentID][Name]
rows[StudentID][City]
etc.

Thanks!

Upvotes: 2

Views: 2812

Answers (2)

Tieson T.
Tieson T.

Reputation: 21231

Depending on which library you are using:

mysql_fetch_assoc()

mysqli_fetch_assoc()

PDO fetches both by default.

Upvotes: 0

Kevin Peno
Kevin Peno

Reputation: 9196

PDOStatement::fetchAll

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.

// Other PDO stuff to get a statement - abstract below
$result = PDOStatement::fetchAll( PDO::FETCH_COLUMN | PDO::FETCH_GROUP, 0 );

See example 3 on this page

Upvotes: 2

Related Questions