Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding database results to array

Tags:

arrays

php

mysql

I am having a mental blank here and cannot for the life of me figure out a solution.

My scenario is that I am programming in PHP and MySQL. I have a database table returning the results for a specific orderid. The query can return a maximum of 4 rows per order and a minimum of 1 row.

Here is an image of how I want to return the results. alt text http://sandbox.mcmedia.com.au/nqlsolutions/images/packages.jpg

I have all the orderdetails (Name, address) ect stored in a table named "orders". I have all the packages for that order stored in a table named "packages".

What I need to do is using a loop I need to have access to each specific element of the database results (IE package1, itemstype1, package2, itemtype2) ect

I am using a query like this to try and get hold of just the "number of items:

$sql = "SELECT * FROM bookings_onetime_packages WHERE orderid = '".$orderid."' ORDER BY packageid DESC";
$total = $db->database_num_rows($db->database_query($sql));

$query = $db->database_query($sql);

$noitems = '';
while($info = $db->database_fetch_assoc($query)){
$numberitems = $info['numberofitems'];

for($i=0; $i<$total; $i++){

$noitems .= $numberitems[$i];

}

}
print $noitems;

I need to have access to each specific element because I them need to create fill out a pdf template using "fpdf".

I hope this makes sense. Any direction would be greatly appreciated.

like image 434
Jason Avatar asked Mar 26 '10 01:03

Jason


1 Answers

You should do something like this:

$data = array();
while($row = $db->database_fetch_assoc($query))
{
    $data[] = $row;
}

Now $data is an array where each element is a row of the query result.

Then you can access the rows as $data[0], $data[1], and the elements within the rows as $data[1]['package'], $data[0]['itemtype'], because each row is an associative array.

You can get the number of rows returned using count($data).

like image 176
David Avatar answered Oct 29 '22 02:10

David