FETCH an array with key-value pairs

If I am retrieving two fields from a table and using a FETCH command to put them into an array, is there a way to make that array have field 1 as the key and field 2 as the associated value to that key? I would like to be able to use array_key_exists later to find rows in that array.

Currently if I use ASSOC I get a numeric key with two named values. Or am I missing something.

I assume I could parse it and create the FETCH array but would prefer avoiding that step. Thanks

Hi bostboy,

You haven’t mentioned which DB extension you’re using, but there is an easy way to do it if you’re using PDO:

$query = $db->query("SELECT `field1` AS name, `field2` AS value FROM `tableA`;");
$array  = $query->fetchAll(PDO::FETCH_KEY_PAIR);

Yes, sorry. Using PDO. I’ll give that a try. Looks like what I am looking for. Many thanks.

Would there be a semi-colon within the parentheses after table name? Not seen that before.

The semi-colon just terminates the SQL statement, but it’s actually not necessary here and can be left off.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.