PHP-SQL如何从表中选择ID并插入到另一个表中? [英] PHP - SQL how to select ids from table and insert into another table?

查看:146
本文介绍了PHP-SQL如何从表中选择ID并插入到另一个表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用insert into语句进行内部联接.我需要将数据插入2个表中,但第二个表中记录的ID也应存储在第一个表中的列中.

I need to do an inner join with the insert into statement. I need to insert data into 2 tables but the id of the records from the second table should also be stored into a column from the first table.

第一个sql部分为dj表中的每个给定dj名称创建一个新记录,第二个部分应该从添加的dj中获取ID,并将其插入到"articles"表中的列中.

the first sql section makes a new record for every given dj name in the dj table, the second part is supposed to get the id from the added dj and insert it into a column from table "articles".

$alle_djs = explode(', ', $this->djs);
foreach ($alle_djs as $elke_dj) {
  $sql = "INSERT INTO dj (name) VALUES ( :name_dj )";
  $st = $conn->prepare($sql);
  $st->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
  $st->execute();

  $sql2 = "INSERT INTO articles (dj_ids) SELECT id FROM dj WHERE name=:name_dj";
  $st2 = $conn->prepare($sql2);
  $st2->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
  $st2->execute();
}
$conn = null

推荐答案

使用LAST_INSERT_ID()函数:

$sql2 = "INSERT INTO articles(dj_ids) VALUES (LAST_INSERT_ID())";

这篇关于PHP-SQL如何从表中选择ID并插入到另一个表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆