我有一個動態的form
,允許用戶輸入信息,並且form
可以多次提交,並且頁面將顯示所有輸入的數據,這要歸功於$_SESSION
。該信息被髮送到另一個頁面,在提交後它將被保存到MySQL數據庫。將動態數組保存到MySQL數據庫
我無法保存所有的信息。如果我有3組數據,它只會將最後一個寫入數據庫。 如何將整個數組保存到數據庫?
這是顯示所有的動態信息的頁面:
<?php
$invoice_no = $_SESSION['invoice'];
if(isset($_SESSION['order'])) :
foreach($_SESSION['order'] as $sav) {
?>
<form action="addrow.php" method="post">
<label>Length</label><input type="text" name="length" value="<?php echo $sav['length']; ?>" size="2">
<label>Width</label><input type="text" name="width" value="<?php echo $sav['width']; ?>" size="2">
<label>Color</label><input type="text" name="color" value="<?php echo $sav['color']; ?>" size="4">
<label>Quantity</label><input type="text" name="quantity" value="<?php echo $sav['quantity']; ?>" size="2">
<label>Invoice Is Hidden</label><input type="hidden" name="invoice" value="<?php echo $invoice_no; ?>">
<input type="hidden" name="total" value="<?php echo $sav['total']; ?>" />
<input type="hidden" name="PaymentStatus" value="PAID">
<br>
<?php } endif; ?>
<br><br>
<input type="submit" value="Submit" name="upload">
</form>
本頁面保存到數據庫中。我不確定如何將數組保存到數據庫中,所以我用同樣的代碼來顯示會話數據和我修改,但沒有成功:
<?php
require("addrow_info.php");
if(isset($_POST['upload'])) :
$decal = array(
'length' => $_POST['length'],
'width' => $_POST['width'],
'color' => $_POST['color'],
'quantity' => $_POST['quantity'],
'total' => $_POST['total'],
'invoice' => $_POST['invoice'],
'paymentStatus' => $_POST['PaymentStatus'],
'submit' => $_POST['upload']
);
$_POST['order'][] = $decal;
endif;
if(isset($_POST['order'])) :
foreach($_POST['order'] as $newOrder) {
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = "INSERT INTO orders (PaymentStatus, invoice_no, length, width, color, quantity, total) VALUES ('".$newOrder['paymentStatus']."','".$newOrder['invoice']."','".$newOrder['length']."', '".$newOrder['width']."', '".$newOrder['color']."', '".$newOrder['quantity']."', '".$newOrder['total']."')";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
echo "$query";
mysql_close();
}
} endif;
header ("location:/thankyou.php");
?>
我在讀有關使用serialize()
功能,但我米不知道這是最好的,我想要完成。我希望每組數據在其各自的列下保存在一行中。
它應該是這樣的:
Length Width Color Invoice Quantity Total PaymentStatus
5 5 Green abc123 1 2.00 PAID <--Each row is a group
6 6 blue def234 2 3.00 PAID
什麼是節約的array
到MySQL數據庫的最佳解決方案?
用於在數據庫中保存的陣列的最佳解決方案是 – Jessica
正常化的數據,從而可以運行適當的查詢。順便提一句,'mysql_query'已過時。看看mysqli或PDO。 – cHao