PHP Arrays and While Loops

Hi

The code I have written pulls in 3 rows from the database and at present puts the values into 1 array. Each row contains 12 values. Is there any way to place them into individual arrays each time it goes through the loop, creating 3 different arrays in total?

The code I am using is:-

$query=mysql_query(“SELECT *FROM table1 WHERE TABLE1.COLUMNID=$value”)

while($row=mysql_fetch_row($query){
some other code…}

Thanks, Shane

Welcome to Sitepoint Shane.

Sure, the following will place all the rows found from the query in the $rows array.


<?php
$res  = mysql_query(/**/);
$rows = array();
while($row = mysql_fetch_assoc($res)){
  array_push($rows, $row);
}

Hi Anthony

Thanks for your prompt reply. I have implemented your code. I have now tried to echo the values of each of the arrays using:-

for($x=0; $x<sizeof($row); $x++){
echo $rows[$x]
}

but it comes back with the word ‘array’.

Thanks again, Shane

Yep, that’s right.

$rows is an array of arrays. :slight_smile:

Let’s say one the columns in your table is id, this is how we’d get at it.


<?php
$res  = mysql_query(/**/);
$rows = array();
while($row = mysql_fetch_assoc($res)){
  array_push($rows, $row);
}


foreach($rows as $row){
  echo $row['id'];
}

Thanks Anthony, works a treat. :slight_smile: