addcustomer.php
<?php
include_once('functions.php');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8s" />
<title>Add Customer</title>
<script type="text/javascript">
function CheckFields()
{
var cusname = document.getElementById("cusname").value;
var cusadd = document.getElementById("cusadd").value;
if(cusname == '')
{
alert("Please enter your customer name");
return false;
}
if(cusadd == '')
{
alert("Please enter your customer address");
return false;
}
return true;
}
</script>
</head>
<body onLoad="focus();add.name.focus()">
<?php
if(array_key_exists('submit_check', $_POST))
{
if($_POST['submit'] == 'Add')
{
if(!AddCustomer(trim($_POST['cusname']), trim($_POST['cusgender']), trim($_POST['cusadd'])))
{
echo "Add Customer Error, Please try it again later";
}
else
{
echo "Customer Information had been successfully added into the database";
}
}
}
else
{
AddCustomerForm();
}
?>
</body>
</html>
dbconnect.php
<?php
$host = "localhost";
$user = "root";
$passwd = "";
$dbname = "customertest";
?>
functions.php
<?php
include('dbconnect.php');
function AddCustomerForm()
{
?>
<form id="add" name="add" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<b><u>Customer Details</u></b><br />
<input type="hidden" name="submit_check" value="1" />
Customer Name : <input type="text" id="cusname" name="cusname" maxlength="50" /><br />
Gender : <input type="radio" name="cusgender" value="M" checked />Male
<input type="radio" name="cusgender" value="F" />Female<br /><br />
<b><u>Customer Address</u></b><br />
Address : <input type="text" id="cusadd" name="cusadd" maxlength="100" size="50" /><br /><br />
<input type="submit" name="submit" value="Add" onclick="return CheckFields();" />
<input type="reset" name="reset" value="Reset" />
</form>
<?php
}
function ConnectToDb()
{
global $host, $user, $passwd, $dbname;
@$db = mysql_pconnect($host, $user, $passwd);
if(!$db)
{
echo "Couldn't connect to the database";
exit;
}
mysql_select_db($dbname);
}
function AddCustomer($cusname, $cusgender, $cusadd)
{
ConnectToDb();
$query = "INSERT INTO customer (cusname, cusgender, cusjoindate) VALUES (\"".$cusname."\", '".$cusgender."', NOW())";
$result = mysql_query($query);
if($result)
{
$cusID = mysql_insert_id();
$query = "INSERT INTO customer_address (cusID, cusaddress) VALUES ('".$cusID."', '".$cusadd."')";
$result = mysql_query($query);
return 1;
}
else
{
return 0;
}
}
?>
从上面的代码中,当我填写客户表单并单击“添加”按钮时,我在数据库中得到了重复记录,如下图所示:
我真的不明白为什么数据库同时存储2条记录。
我写错代码了吗?有人能帮我吗?
最佳答案
您是否正确分配了主键和外键。指的是客户地址表中的cusID,它引用了客户表中的cusID(主键)。
更改表customer_address
添加外键(cusID
)参考customertest
。customer
(cusID
)启用删除限制,启用更新限制;