我有一个动态的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