請有人幫助我。我有這樣的問題:將數據庫表存儲到數組php
我想從數據庫中獲取數據並將其存儲在數組中。例如:
我的產品表:
ID ::名::價格::數量
1 ::紅舞鞋:: 10 :: 2
2 ::黑裙子:: 20 :: 3
3 ::藍裙:: 30 :: 1
我想從該表獲得的數據在陣列的存儲這樣的:
$items = [
array(
'id' => '1',
'price' => 10,
'quantity' => 2,
'name' => 'Red Shoes'
),
array(
'id'=> '2',
'price' => 20,
'quantity' => 3,
'name' => 'Black Dress'
),
array(
'id'=> '3',
'price' => 30,
'quantity' => 1,
'name' => 'Blue Skirt'
)
];
我嘗試使用此代碼:
$query = mysql_query("SELECT * FROM product");
$data_item = array();
while ($row = mysql_fetch_array($query)) {
$data_item['id'] = $row['id'];
$data_item['price'] = $row['price'];
$data_item['quantity'] = $row['qty'];
$data_item['name'] = $row['name'];
}
$items = [$data_item];
print_r($items);
這是輸出:
Array ([0] => Array ([id] => 3 [price] => 30 [quantity] => 1 [name] => Blue Skirt))
與該代碼我只是得到最後的數據和2個其他沒有內部陣列存儲。爲什麼會發生?
如何獲得輸出這樣的:
Array ([0] => Array ([id] => 1 [price] => 10 [quantity] => 2 [name] => Red Shoes) [1] => Array ([id] => 2 [price] => 20 [quantity] => 3 [name] => Black Dress) [2] => Array ([id] => 3 [price] => 30 [quantity] => 1 [name] => Blue Skirt) )
有人能幫助我嗎?
+1表示不贊成使用的mysql。 –