doukan5332 2016-09-23 14: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 14: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

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

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部