1
我是PHP-MySQL
新手,當我嘗試從另一個表格中顯示dropdown
字段值並將其保存到當前表格中時,會遇到問題。我在網上發現了一個完整的CRUD教程,但它只有簡單的創建,更新,顯示功能只使用輸入字段,沒有選擇字段,和其他複雜的東西。保存從一個表格到另一個表格的下拉菜單中顯示的數據
目前,我有2個表:
客戶,具有以下字段:
customer_id, customer_name, customer_address, customer_country
。訂單,與字段:
order_id, customer_id, product_name, product_price, product_qty
。
具有以下orders.php
我想用一個dropdown
爲customer_id
顯示customer_name
從客戶表和選擇客戶名稱保存它在當前表的(訂單)customer_id
customer_id
場。
<?php
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($customerid, $productname, $productprice, $productqty, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<title>ORDERS</title>
</head>
<body>
<form action="" method="post">
<label for="customer_id">Customer ID:* </label>
<select name="customer_id">
<?php
$sql = "SELECT * FROM customers ORDER BY customer_name ASC;";
$res = mysql_query($sql);
while($row= mysql_fetch_assoc($res)) {
echo "<option value='" . $row['customer_id']
. "'>" . $row['customer_name'] . "</option>";
}
?>
</select>
<label for="product_name">Product name:*</label>
<input type="text" name="product_name" value="<?php echo $productname; ?>" /><br/>
<label for="product_price">Price:* </label>
<input type="text" name="product_price" value="<?php echo $productprice; ?>" /><br/>
<label for="product_qty">Qty:* </label>
<input type="text" name="product_qty" value="<?php echo $productqty; ?>" /><br/>
<input type="submit" name="submit" class="btn-global" value="Save">
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$id = mysql_real_escape_string(htmlspecialchars($_POST['customer_id']));
$product = mysql_real_escape_string(htmlspecialchars($_POST['product_name']));
$price = mysql_real_escape_string(htmlspecialchars($_POST['product_price']));
$qty = mysql_real_escape_string(htmlspecialchars($_POST['product_qty']));
// check to make sure both fields are entered
if ($id == '' || $product == '' || $price == '' || $qty == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($customerid, $productname, $productprice, $productqty, $error);
}
else
{
// save the data to the database
mysql_query("INSERT orders SET customer_id='$id', product_name='$product', product_price='$price', product_qty='$qty'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: some.php");
}
}
else // if the form hasn't been submitted, display the form
{
renderForm('','','','','');
}
?>
你做了什麼錯誤? –
你在混淆UPDATE和INSERT – Strawberry