3

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:

$products["f84jjg"]["name"]

$products["245"]["code"]

I've tried using the following code but it doesn't work:

while ($row = mysql_fetch_row($sqlresult)) { $products = array($row[0] => array( name => $row[1], code => $row[2] ) ); } 

Also, how should I reference the key if it is taken from a variable? What I want to do is:

$productName = $products[$thisProd]["name"]; 

Will this work?

1 Answer 1

8

This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):

while($row = mysql_fetch_row($sqlresult)) { $products[$row[0]] = array( 'name' => $row[1], 'code' => $row[2] ); } 

You need to put quotes around the array keys, and you were creating an array of array of arrays.

Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:

while($row = mysql_fetch_assoc($sqlresult)) { $products[$row['myidcolumn']] = $row; } 

After you do this, the code you described would work.

Sign up to request clarification or add additional context in comments.

Comments