我有一个表单和三个表:customer
, phone_number
和junction
(创建多对多关系)。
我需要表单来填充所有三个表,使用从customer
和phone number
表中新创建的自动递增的id来填充junction
表中的customer_id
和phone_id
列。
我想出了以下方法,这将从customer
表中插入新创建的id到junction
表中,但我不知道如何让电话号码做同样的事情。
$query = "INSERT INTO customer (first_name, last_name) VALUES (%s, %s)",
GetSQLValueString($_POST['first_name'], "text"),
GetSQLValueString($_POST['last_name'], "text"));
$result = mysql_query();
$insertID = mysql_insert_id();
$query = "INSERT INTO junction (customer_id) VALUES ($insertID)";
mysql_select_db($database_hh, $hh);
$result = mysql_query($query, $hh) or die(mysql_error());
下面是给你的伪代码:
//Insert a customer
$query = "INSERT INTO `customer` ..."
...
//Get the newly inserted customer's ID
$customer_id = mysqli_insert_id();
//Insert a phone
$query = "INSERT INTO `phone` ..."
...
//Get the newly inserted phone's ID
$phone_id = mysqli_insert_id();
...
//Insert them in the junction table
$query = "INSERT INTO `junction` (customer_id, phone_id) VALUES ($customer_id, $phone_id)"
由于你使用的是mysql_*
这是你在stackoverflow上可能经常看到的注释:
请不要在新代码中使用mysql_*函数。它们不再被维护,社区已经开始弃用过程。看到那个红框了吗?相反,您应该学习预处理语句,并使用PDO或mysql。如果你不能决定,这篇文章将帮助你做出选择。如果你想学习,这里有很好的PDO教程。