我一直在为自己拥有的公司工作的网站上工作,但对PHP和SQL感到有些生疏。我可以在PHP中创建自己想要的样板店/库存数组,但是我一直试图将MySQL数据库中的表数据插入到我的PHP数组中。我想做的是复制我的模型,但是,我不想从我在15 == 1|2|10
中定义的数组中提取数据,而是想从我在MySQL中创建的表中提取数据。
模型如下:
shop.php(当前):
inventoryArray.php
inventoryArray.php(之前):
<?php foreach ($inventory as $handgun) {?>
<div class="column">
<h5><?php echo "$handgun[model]"?></h5>
<img class="thumbnail"
src="assets/style/images/inventory/pistols/<?php echo "$handgun[img]" ?>.png">
<table class="shopTables">
<tr>
<th>MPN:</th>
<td><?php echo "$handgun[mpn]"?></td>
</tr>
<tr>
<th>UPC:</th>
<td><?php echo "$handgun[upc]"?></td>
</tr>
<tr>
<th>Accessories:</th>
<td><?php echo "$handgun[accessories]"?></td>
</tr>
<tr>
<th>Description:</th>
<td><?php echo "$handgun[description]"?></td>
</tr>
</table>
<a href="product-page.php" class="button expanded">View</a>
</div>
<?php } ?>
我没有对 <?php
$inventory = array(
array(
'action' => "Striker-fired",
'category' => "Pistols",
'cal_ga' => "9mm",
'manufacturer' => "FN Herstal",
'model' => "FN 509 Midsize",
'UPC' => "845737010010",
'img' => "FN509M",
'price' => "$649"
),
array(
'action' => "SA/DA",
'category' => "Pistols",
'cal_ga' => "9mm",
'manufacturer' => "CZ USA",
'model' => "CZ P01",
'UPC' => "806703911991",
'img' => "CZP01",
'price' => "$627"
)
);
?>
进行任何更改,以下是我尝试使用shop.php
文件中MySQL表中的数据的方法:
inventoryArray.php(之后):
inventoryArray.php
尽管这会将数据从我的表插入到我的数组中,但是将新清单插入到SQL表中将不会创建类似于我的模型的新嵌套数组。相反,它似乎会覆盖原始数组。
答案 0 :(得分:4)
只需将行的关联数组提取到新数组中并动态附加到它:
while ($row = mysqli_fetch_assoc($response)) {
$inventory[] = $row;
}
您真的可以这样做:
while ($inventory[] = mysqli_fetch_assoc($response));
如果表中还有更多列,并且您不想(没关系),则仅选择想要的列:
$query = "SELECT model, img, mpn, upc, accessories, description FROM firearms";
答案 1 :(得分:1)
正在覆盖,因为您在每个循环上定义变量。代替
while ($row= mysqli_fetch_array($response)) {
$inventory = array(
array(
'model' => $row['model'],
'img' => $row['img'],
'mpn' => $row['mpn'],
'upc' => $row['upc'],
'accessories' => $row['accessories'],
'description' => $row['description']
)
);
}
在循环之前定义$inventory
,然后使用$inventory[]
$inventory = array();
while ($row= mysqli_fetch_array($response)) {
$inventory[] =
array(
'model' => $row['model'],
'img' => $row['img'],
'mpn' => $row['mpn'],
'upc' => $row['upc'],
'accessories' => $row['accessories'],
'description' => $row['description']
);
}