0

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
Enes Yurtlu
  • 15
  • 1
  • 3
  • Please don't add things like "Solved" to the title. If you found a solution mark that answer as accepted. – tadman Sep 24 '16 at 00:21
  • **WARNING**: When using PDO you should be using [prepared statements](http://php.net/manual/en/pdo.prepared-statements.php) with placeholder values and supply any user data as separate arguments. In this code you have potentially severe [SQL injection bugs](http://bobby-tables.com/). Never use string interpolation or concatenation and instead use [prepared statements](http://php.net/manual/en/pdo.prepared-statements.php) and never put `$_POST` or `$_GET` data directly in your query. Refer to [PHP The Right Way](http://www.phptherightway.com/) for guidance with this and other problems. – tadman Sep 24 '16 at 00:21

1 Answers1

1

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

L00_Cyph3r
  • 669
  • 4
  • 18