Page 1 of 1

Newbie question - creating arrays from multiple rows

Posted: Thu Sep 28, 2006 2:46 pm
by hanuman
Hi. Can anyone help?

I've got the following table:

product_id dimensions weight
45 35x24x13 3.95
45 24x12x6 2.76

I need to retrieve all the different dimensions-weight pairs for the same product_id.

My code is as follows:

$size_weight_query = mysql_query("select dimensions, weight from " . TABLE_SIZE_WEIGHT_PAIRS . " where product_id = 45");
$size_weight_query_array = mysql_fetch_array($size_weight_query);

with this set up, $size_weight_query_array['dimensions'] and $size_weight_query_array['weight'] only contain one
element each - the data from the first row only. I need each of these arrays to contain ALL the 'dimensions' and 'weight's
from every row which has the same product_id

I'd be really grateful for any help - the remainder of my hair is under serious threat.

Regards

Nick

Posted: Thu Sep 28, 2006 2:51 pm
by volka
mysql_fetch_array returns the next record from the result set. Therefore you have to fetch records until there are no more (mysql_fetch_array returns false). You can append each record to an existing array.

Code: Select all

<?php
$size_weight_query = mysql_query("select dimensions, weight from " . TABLE_SIZE_WEIGHT_PAIRS . " where product_id = 45");

$size_weight_query_array = array();
while ( $row=mysql_fetch_array($size_weight_query) ) {
	$size_weight_query_array[] = $row;
}

echo "<pre>\n", var_export($size_weight_query_array, true), "\n</pre>";
?>

thanks a lot

Posted: Fri Sep 29, 2006 6:45 am
by hanuman
Volka! That's perfect! Thank you so much - keep up the good work.

Nick

Posted: Fri Sep 29, 2006 9:43 am
by impulse()
For benefit of my learning curve - Why do you define $size_weight_query_array as an array before you let mysql_fetch_array put it into an array?

Is this something to do with actually putting each row into [0], [1] etc etc?


[/b]

Posted: Fri Sep 29, 2006 10:19 am
by volka
$size_weight_query_array[]
appends a new element to the array $size_weight_query_array.
Therefore we make $size_weight_query_array an array before the first use of []