CLiown
CLiown

Reputation: 13843

Fetch all rows based on the query into an array

I have the following code:

  //--------------------------------------------------------------------------
  // 2) Query database for data
  //--------------------------------------------------------------------------
  $result = mysql_query("SELECT * FROM $tableName");          //query
  $array = mysql_fetch_row($result);                          //fetch result   

  //--------------------------------------------------------------------------
  // 3) echo result as json 
  //--------------------------------------------------------------------------
  echo json_encode($array);

What I would like to do is fetch all rows based on the query and feed those into the array, to give me an output like this:

["1", "", "", "", "", ""]
["2", "", "", "", "", ""]
etc...

I presume I need to loop through the rows and build up the array but I don't know how.

Upvotes: 0

Views: 11096

Answers (2)

Stefan
Stefan

Reputation: 3900

$result = mysql_query("SELECT * FROM $tableName");  
$arr_json = array();
while ($row = mysql_fetch_assoc($result)) {
   $json = json_encode($row);
   $arr_json[] = $json;
}

EDIT: Looking a j08691's answer, it looks like I might have misunderstood.

Anyway, if you don't know how many columns you have, do this:

$arr = array();
while ($row = mysql_fetch_assoc($result)) {
   $arr2 = array();
   foreach ($row as $val) $arr2[] = $val;
   $arr[] = $arr2;
}

Upvotes: 1

j08691
j08691

Reputation: 207901

Try:

$result = mysql_query("SELECT * FROM $tableName");
while($row = mysql_fetch_array($result)) {
    $array[]=array($row[0], $row[1],...);
}

This will generate a multidimentional array where the subarray contains your values.

Upvotes: 0

Related Questions