我已經寫了一個PHP程序,用於查詢MySQL數據庫以填充下拉列表,然後提供將值插入第三個表的選項。它幾乎可以工作,但不是將值插入到一條記錄中,而是單獨插入它們,即使它是一個查詢。我該如何補救?PHP從MySQL表中選擇並保存在另一個表中
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php // add-order.php
date_default_timezone_set("Australia/Adelaide");
$datetry= date("Y/m/d");
echo "today's date is ".$datetry."<br>";
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query="SELECT * FROM customers";
$result=$conn->query($query);
if (!$result) die($conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
$Customers[$j][0] = $row[0];
$Customers[$j][1]= $row[1];
$Customers[$j][2]= $row[2];
}
?>
<form action="add-order.php" method ="post">
<select name="choice">
<option selected="selected">Choose a customer</option>
<?php
for ($j = 0 ; $j < $rows ; ++$j){
?>
<option value="<?php echo $Customers[$j][0]; ?>"><?php echo $Customers[$j][1]; ?></option>
<?php
}
?>
</select>
<input type="submit" value="submit">
</form>
<?php
$result->close();
//products array
$queryp="SELECT * FROM products";
$resultp=$conn->query($queryp);
if (!$resultp) die($conn->error);
$rows = $resultp->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$resultp->data_seek($j);
$row = $resultp->fetch_array(MYSQLI_NUM);
$Products[$j][0] = $row[0];
$Products[$j][1]= $row[1];
}
?>
<form action="add-order.php" method ="post">
<select name="choice1">
<option selected="selected1">Choose a product</option>
<?php
for ($j = 0 ; $j < $rows ; ++$j){
?>
<option value="<?php echo $Products[$j][0]; ?>"><?php echo $Products[$j][1];
?></option>
<?php
}
?>
</select>
<input type="submit" value="submit">
</form>
<?php
$resultp->close();
$PresentCustomer = $_POST['choice'];
echo $PresentCustomer;
$PresentProduct = $_POST['choice1'];
echo $PresentProduct;
$queryO = "INSERT INTO orders VALUES('','$PresentCustomer', '$PresentProduct','$datetry')";
$resultO = $conn->query($queryO);
if (!$resultO) echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
$resultO->close();
$conn->close();
?>
</body>
</html>
您從不指定數據應插入的列。 INSERT INTO表(可樂,colb等)VALUES('val1','val2'等)' – Xorifelse
@Xorifelse如果值列表包含所有列的名義順序值,則不需要指定列。 – Shadow
@Shadow很正確,但如果情況並非如此,會發生什麼? – Xorifelse