Alex311
Alex311

Reputation: 21

MYSQL Insert a primary key in another table as foreign key

I'm trying to add a few Primary Keys from different tables as Foreign Keys to one Main table in a Query in php.

So far I got:

$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id,  M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
                              . "VALUES (DEFAULT, 123,  123, '".$_SESSION['sId']."' , 123, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', 123,"
                              . "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."')");

Every "123" I want to replace with an existing Primary key from other tables from my database. How is this possible ?

Upvotes: 1

Views: 3478

Answers (2)

Alex311
Alex311

Reputation: 21

A long time ago I asked this question. Finally I found some time to answer it in case anybody has the same problem. Don't know why I wanted to make it so complicated. Subquerys where the answer:

$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id,  M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
                          . "VALUES (DEFAULT, (SELECT MAX id FROM title), (((AND SO ON...)))

Upvotes: 1

ForguesR
ForguesR

Reputation: 3618

You can use the INSERT ... SELECT syntax.

Something like this where anotherTable is the other table you want to insert from.

$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id,  M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar) "
                     . "SELECT (DEFAULT, anotherTable.id,  anotherTable.id, '".$_SESSION['sId']."' , anotherTable.id, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', anotherTable.id,"
                     . "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."') FROM anotherTable");

If needed you can also limit the number of inserted rows into m_main with a WHERE clause in the SELECT statement.

Upvotes: 1

Related Questions