简体   繁体   English

在数据库PHP中一次插入两个表

[英]Insert two tables together at once in database PHP

I just wondering if there is a possibility to insert into the database two tables at once like, 我只是想知道是否有可能一次性插入数据库两个表,如,

$query = sprintf("INSERT INTO table ('tableid')values('somevaleu'),INSET INTO table1 ('table1id')values('somevalue')");

or I need to do it separately like, 或者我需要单独做,像,

$query1 = sprintf("INSERT INTO table ('tableid')values('somevaleu')");
$query2 = sprintf("INSET INTO table1 ('table1id')values('somevalue')");

Any suggestions? 有什么建议么?

If you are using the old mysql extension ( mysql_* functions), then you cannot issue multiple queries in one statement. 如果您使用旧的mysql扩展( mysql_*函数),那么您不能在一个语句中发出多个查询。

From the manual 1 : 从手册1

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier. mysql_query()向与指定link_identifier关联的服务器上的当前活动数据库发送唯一查询(不支持多个查询)。

If you were using mysqli or pdo mysql then you can do multiple inserts in one query. 如果你使用mysqlipdo mysql,那么你可以在一个查询中进行多次插入。

It would also be possible to insert multiple rows into the same table in one query using extended inserts, but not two different tables. 也可以使用扩展插入在一个查询中将多行插入同一个表,但不能在两个不同的表中插入。

Why are you trying to do this? 你为什么要这样做? If it's just laziness, please just take the extra thirty seconds and use two separate statements. 如果它只是懒惰,请花费额外的30秒并使用两个单独的声明。 If, OTOH, you want to do this because you need to make both inserts at the same time to keep your database consistent (eg updating an "orders" table and a "billing" table at the same time), you want to look into transactions . 如果,OTOH,你想这样做是因为你需要同时进行两次插入以保持数据库的一致性(例如同时更新“订单”表和“计费”表),你想要查看交易

Basically, a transaction (started with BEGIN ) is a bunch of queries that get bundled together and, when you're done, you can either COMMIT and make them stick or ROLLBACK to throw them away (such as if there's an error and you want to abort the process). 基本上,一个事务(以BEGIN开头)是一堆捆绑在一起的查询,当你完成后,你可以COMMIT并使它们坚持或ROLLBACK将它们抛弃(例如,如果有错误,你想要中止这个过程)。 They're not exactly executed at the same time but, on a COMMIT, they will either all succeed or none of them will go through. 它们并不是在同一时间完全执行,但是在COMMIT上,它们要么全部成功,要么都不会通过。

You can use begin to enclose multiple SQL statements: 您可以使用begin来包含多个SQL语句:

$query = "BEGIN ";
$query .= "INSERT INTO table ('tableid')values('somevalue') INSERT INTO table1 ('table1id')values('somevalue') ";
$query .= "COMMIT";

Then run $query . 然后运行$query

It depends on how your database is being queried. 这取决于您的数据库的查询方式。 A lot of the 3rd-party database abstraction libraries I've used only allow one SQL statement per execution. 我使用的很多第三方数据库抽象库每次执行只允许一个SQL语句。 But MySQL can accept multiple queries separated by a semicolon, as you propose. 但是,正如您所建议的那样,MySQL 可以接受由分号分隔的多个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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