我正在尝试将表单中的数据提交到两个单独的表。
这是错误:它可以很好地插入表 1,但表 2 数组数据作为“数组”进入数据库。
这是我进入 table1 的字段:
$start = $_POST['start'];
$end = $_POST['end'];
$customer = $_POST['customer'];
$manufacturer = $_POST['manufacturer'];
$rep = $_POST['rep'];
$notes = $_POST['notes'];
我的数组字段进入 table2:
item[]
description[]
pack[]
任何帮助表示赞赏。以下是我迄今为止开发的代码:
if ($start == '' || $end == '')
{
$error = '<div class="alert alert-error">
<a class="close" data-dismiss="alert">×</a>
<strong>Error!</strong> Please fill in all required fields!
</div>';
}
else
{
$sql = "SELECT COALESCE(MAX(GroupID), 0) + 1 AS newGroupID FROM table1";
try
{
$stmt = $db->prepare($sql);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach($rows as $row) {
$groupID = $row['newGroupID'];
}
$mysqli = new mysqli("localhost", "user", "pw", "mydb");
if (mysqli_connect_errno()) {
die(mysqli_connect_error());
}
$start = $_POST['start'];
$end = $_POST['end'];
$customer = $_POST['customer'];
$manufacturer = $_POST['manufacturer'];
$rep = $_POST['rep'];
$notes = $_POST['notes'];
if ($stmt = $mysqli->prepare("INSERT table1 (GroupID, start, end, customer, manufacturer, rep, notes) VALUES (?, ?, ?, ?, ?, ?, ?)"))
{
$stmt->bind_param("issssss", $groupID, $start, $end, $customer, $manufacturer, $rep, $notes);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement 1.";
}
$mysqli->error;
$mysqli->close();
$success = "<div class='alert alert-success'>New agreement added.</div>";
$mysqli = new mysqli("localhost", "user", "pw", "mydb");
if (mysqli_connect_errno()) {
die(mysqli_connect_error());
}
if ($stmt = $mysqli->prepare("INSERT table2 (GroupID, item_number, item_description, pack) VALUES (?, ?, ?, ?)"))
{
foreach($_POST['item'] as $i => $item) {
$item = $_POST['item'];
$description = $_POST['description'];
$pack = $_POST['pack'];
}
$stmt->bind_param("isss", $GroupID, $item, $description, $pack);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement 2.";
}
$mysqli->error;
$mysqli->close();
$success = "<div class='alert alert-success'>New agreement items added!</div>";
}
}