【发布时间】:2020-03-03 21:45:17
【问题描述】:
我有两个表,在表 1 中,有一个自动增量 ID,我想在记录保存到表 1 后立即将最后一个 ID 插入表 2。是否可以这样做。我有一个用户填写的表格,然后在提交时将收集的数据提交到两个不同的表格。 这是我插入数据的代码
class.php
public function insertID(){
$query = "INSERT INTO table_1 SET book_name=:book_name; INSERT INTO table_2 SET
book_type=:book_type, book_type_id=:book_type_id";
$stmt = $this->conn->prepare($query);
$this->book_name=$this->name; //this data came from a form
$this->book_type=$this->book_type; //same as this one
$this->book_type_id=(Im not sure what to put here)(I tried LAST_INSERT_ID and
mysqli_insert_id)
//data the will go here should come from the last inserted ID so I connect table 1 and
table 2 using this ID
$stmt->bindParam(':book_name', $this->book_name);
$stmt->bindParam(':book_type', $this->book_type);
$stmt->bindParam(':book_type_id', $this->book_type_id);
if($stmt->execute()){
return true;
}else{
return false;
}
}
这是我的表格
include_once 'class.php';
$class = new Class($db);
if($_POST){
$class->book_name=$_POST['book_name'];
$class->book_type=$_POST['book_type'];
if($class->insertId()){
echo "saved";
}else {
not saved
}
}
任何建议将不胜感激。
这是我在@GMB 的帮助下的解决方案
class.php
public function insertID(){
$query_1 = "INSERT INTO table_1
SET book_name=:book_name";
$stmt_1 = $this->conn->prepare($query_1);
$this->book_name=$this->book_name;
$stmt_1->bindParam(':book_name', $this->book_name);
if($stmt_1->execute()){
$query_2 = "INSERT INTO table_2
SET book_type=:book_type, book_type_id=:book_type_id";
$stmt_2 = $this->conn->prepare($query_2);
$this->book_type=$this->book_type;
$this->book_type_id=$this->conn->lastInsertId();
$stmt_2->bindParam(':book_type', $this->book_type);
$stmt_2->bindParam(':book_type_id', $this->book_type_id);
if($stmt_2->execute()){
return true;
}else{
return false;
}
}else{
return false;
}
}
【问题讨论】:
-
你需要执行两个不同的语句。
-
如何将它集成到我的函数中?
-
感谢@FunkFortyNiner 的帮助,
标签: php mysql sql sql-insert