doukan5332 2016-09-23 22:48
浏览 28
已采纳

PDO从不同的表中获取当前添加的ID? [重复]

This question already has an answer here:

I changed the order and it worked. Like this:

$sql_b = "INSERT INTO h_baslik (h_baslik_t) VALUES ('$hbaslik')";
$sql_s = "INSERT INTO h_spot (h_spot_t) VALUES ('$hspot')";
$sql_m = "INSERT INTO h_metin (h_metin_t) VALUES ('$hmetin')";
$sql_r = "INSERT INTO h_resim (h_resim_url) VALUES ('$hresim')";


$conn->exec($sql_b);
$hbaslik_id = $conn->lastInsertId();
$conn->exec($sql_s);
$hspot_id = $conn->lastInsertId();
$conn->exec($sql_m);
$hmetin_id = $conn->lastInsertId();
$conn->exec($sql_r);
$hresim_id = $conn->lastInsertId();
$sql_h = "INSERT INTO haberler (baslik, spot, metin, resim, kat_id, yayin_zamani, onay) VALUES ('$hbaslik_id', '$hspot_id', '$hmetin_id', '$hresim_id', '$hkat', '$htarih', '$honay')";
$conn->exec($sql_h);

here is the code that i tried so many different styles. I want to add news content to e.g. "content" table. News Title to "titles" table. and then i want to get ids' of that records to my "news" table as int value (ids). How can i do that with PDO.

</div>
  • 写回答

1条回答 默认 最新

  • dourang6858 2016-09-23 22:59
    关注

    The function lastInsertId() returns the last inserted ID of the connection. So you'll need to fetch the ID after every insert.

    $sql_b = "INSERT INTO h_baslik (h_baslik_t) VALUES ('$hbaslik')";
    $sql_s = "INSERT INTO h_spot (h_spot_t) VALUES ('$hspot')";
    $sql_m = "INSERT INTO h_metin (h_metin_t) VALUES ('$hmetin')";
    $sql_r = "INSERT INTO h_resim (h_resim_url) VALUES ('$hresim')";
    
    $sql_h = "INSERT INTO haberler (baslik, spot, metin, resim, kat_id, yayin_zamani, onay) VALUES ('$hbaslik_id', '$hspot_id', '$hmetin_id', '$hresim_id', '$hkat', '$htarih', '$honay')";
    
    $conn->exec($sql_b);
    $hbaslik_id = $conn->lastInsertId();
    $conn->exec($sql_s);
    $hspot_id = $conn->lastInsertId();
    $conn->exec($sql_m);
    $hmetin_id = $conn->lastInsertId();
    $conn->exec($sql_r);
    $hresim_id = $conn->lastInsertId();
    
    $conn->exec($sql_h);
    

    PDO::lastInsertId on php.net

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?