Graeme Leighfield
Graeme Leighfield

Reputation: 2985

Combining two PHP sql statements into one

I'm after a little help in the quest for cleaner code...

Current code which is working fine. Wondering if I can make it into one SQL statement as opposed to two...

$sql = "INSERT INTO table_a (1,2,3,4) VALUES ('$1','$2','$3','$4');";

$result = mysql_query($sql,$mysql_link);

$id = mysql_insert_id();

$sql2 = "INSERT INTO table_b (1,2,3,4) VALUES ('$id','$5','$6','$7');";

$result2 = mysql_query($sql2,$mysql_link);

How can I combine these two to work within my current php script?

Thanks!

Upvotes: 0

Views: 758

Answers (3)

Vilius Ramanauskas
Vilius Ramanauskas

Reputation: 48

As mentioned above, you can't combine them, because inserts are in 2 different tables, although you could write a stored procedure (with necessary parameters) containing both of these queries and call that procedure in PHP instead of writting those statements... It would help to tell the reason you want to do that, because i can't understand if you want to get more compact (reusable) code, or improve the performance of your DB...

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157839

When I see another question of this kind, I am always wondering, why noone asks how to combine ALL sql queries of the script into one. All SELECTs, INSERTS, UPDATES. Wouldn't it be logically?

What's the strange desire to combine? What's the point in it? What's wrong in 2 separate queries?

When you eat, do you mix a salad, a soup, a main dish, a drink into one bowl and then consume it? No? Why do you want to put all the queries into same bowl then?

Upvotes: 1

prehfeldt
prehfeldt

Reputation: 2182

An insert in two different tables is not possible. If you want to reduce your query count you may have to reconsider your database structure.

Upvotes: 2

Related Questions