【发布时间】:2020-03-09 08:00:08
【问题描述】:
早安,
我有这个 foreach 循环,一个变量值 (p_id) 从另一个表中分配给前一个插入的 lastInsertId()。假设我有两个表,table_a 用于人员列表,table_b 用于他们拥有的书籍列表。
p_id – is the id of the person from table_a
b_title – is the title of the book
b_genre is the genre of the book
假设我在 table_a 中添加了一个新人,他的名字是 Jerry,他的 ID 或 p_id 是 333。所以由于 Jerry 是最后一个包含在列表中的人,他的 p_id 是 333 现在是 lastInsertId() .然后假设 Jerry 拥有两本书,我现在将它们记录到 table_b 这是一个人拥有的书籍列表。
这是我将如何使用动态添加/删除输入框插入图书名称和类型的代码。
$query_1 = “some_mysql_code_that_will_insert_data_to_table_a”;
$stmt_1 = $this->conn->prepare($query_1);
if($stmt_1->execute()){
//run this code under
foreach($p_name AS $key => $value) {
$query_2 = "INSERT INTO
table_b
SET
p_id=:p_id,
b_title = :b_title,
b_genre = :b_genre";
$stmt _2= $this->conn->prepare($query);
$p_id=$this->conn->lastInsertId();
$b_title=$value;
$b_genre = $b_genre[$key];
$stm_2->bindParam(':p_id', $p_id);
$stm_2t->bindParam(':b_title', $b_title);
$stmr_2->bindParam(':b_genre', $b_genre);
$stmt_2->execute();
}
}
问题是我只能将 lastInsertId() 插入一次,ID 333 到列 p_id。
为了帮助您在此处进行可视化,这里是 table_b 的示例。
+--------+---------+---------+---------+
| b_id | p_id | b_title | b_genre |
+--------+---------+---------+---------+
| 1 | 333 | Carrie | Horror |
现在的问题是当我插入第二个数据或 Jerry 拥有的第二本书时。
这就是发生的事情。
+--------+---------+---------+---------+
| b_id | p_id | b_title | b_genre |
+--------+---------+---------+---------+
| 1 | 333 | Carrie | Horror |
+--------+---------+---------+---------+
| 2 | 1 | Dune | Scifi |
我怎样才能使上面的表格看起来像这样,具有相同的 p_id。
+--------+---------+---------+---------+
| b_id | p_id | b_title | b_genre |
+--------+---------+---------+---------+
| 1 | 333 | Carrie | Horror |
+--------+---------+---------+---------+
| 2 | 333 | Dune | Scifi |
谢谢。
【问题讨论】: