PDO从不同的表中获取当前添加的ID?

时间:2016-09-23 22:48:56

标签: php mysql pdo

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);

这是我尝试了很多不同风格的代码。 我想将新闻内容添加到例如“内容”表。新闻标题为“标题”表。然后我想把那些记录的ids'作为int值(ids)送到我的“新闻”表。我怎么能用PDO做到这一点。

1 个答案:

答案 0 :(得分:1)

函数lastInsertId()返回最后插入的连接ID。 因此,您需要在每次插入后获取ID。

$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