
[英]php mysql how to use mysql_insert_id() to be able to insert into 2 table at the same time?
[英]How to use mysql_insert_id with a junction table
我有一个表格和三个表: 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_*
这里的注释可能会在StackOveflow上看到很多:
请不要对新代码使用mysql_ *函数。 它们已不再维护,社区已开始弃用过程 。 看到红色框了吗? 相反,您应该了解准备好的语句,并使用PDO或MySQLi 。 如果您不能决定, 本文将有助于选择。 如果您想学习,这里有个不错的PDO教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.