doushang2021 2015-09-24 11:06
浏览 61
已采纳

PHP - SQL如何从表中选择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.

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
  • 写回答

1条回答 默认 最新

  • douzong3599 2015-09-24 11:35
    关注

    Use the LAST_INSERT_ID() function:

    $sql2 = "INSERT INTO articles(dj_ids) VALUES (LAST_INSERT_ID())";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部