简体   繁体   中英

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!

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.

如上所述,您无法将它们组合在一起,因为插入位于2个不同的表中,尽管您可以编写包含两个查询的存储过程(带有必要的参数)并在PHP中调用该过程,而不用编写这些语句...这将有助于告诉您您要执行此操作的原因,因为我无法理解您是否想要获得更紧凑(可重用)的代码,或者提高数据库的性能...

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM