php 将数据库结果添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2520720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:48:32  来源:igfitidea点击:

Adding database results to array

phpmysqlarrays

提问by Jason

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.

我的情况是我正在使用 PHP 和 MySQL 进行编程。我有一个数据库表,返回特定 orderid 的结果。查询每个订单最多可以返回 4 行,最少可以返回 1 行。

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

这是我想要如何返回结果的图像。 替代文字 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

我需要做的是使用一个循环,我需要访问数据库结果的每个特定元素(IE package1、itemtype1、package2、itemtype2)等

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".

我需要访问每个特定元素,因为我需要使用“fpdf”创建填写 pdf 模板。

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

我希望这是有道理的。任何方向将不胜感激。

回答by David

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.

现在 $data 是一个数组,其中每个元素都是查询结果的一行。

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.

然后,您可以以 $data[0]、$data[1] 的形式访问行,以 $data[1]['package']、$data[0]['itemtype'] 的形式访问行中的元素,因为每个row 是一个关联数组。

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

您可以使用 count($data) 获取返回的行数。