doushang2021 2015-09-24 19: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 19:35
    关注

    Use the LAST_INSERT_ID() function:

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序