问题
There is any way to update two tables in one query? Below is an example of my code. How can I put those two update queries in one? Thank you in advance!
<?php
// DATABASE UPDATE
if (isset($_POST['submit']) or isset($_GET['submit'])){
// 1st QUERY
$db =& JFactory::getDBO();
$query_1 = "UPDATE table_1
SET name = '".$_POST["name"]."',
surename = '".$_POST["surename"]."'
WHERE id=1";
$db->setQuery($query_1);
$db->query();
// 2nd QUERY
$db =& JFactory::getDBO();
$query_2 = "UPDATE table_2
SET team_id = '".$_POST["team_id"]."',
SET team_name = '".$_POST["team_name"]."'
";
$db->setQuery($query_2);
$db->query(); } ?>
回答1:
MySQL does actually allow updates to multiple tables in a single query (although often it makes sense for your application to do one at a time).
UPDATE table_1, table_2
SET table_1.field = <some value>, table_2.field = <some value>
WHERE table_1.field2 = table_2.field_2
AND table_1.field_3 = <some other value>
See: http://dev.mysql.com/doc/refman/5.1/en/update.html
As other people have stated, you should look at using prepared statements.
回答2:
Use a transaction, only the InnoDB engine supports it.
mysql> start transaction; Query OK, 0 rows affected (0.00 sec)
{First Insert here}
{Second Insert Here}
mysql> commit; Query OK, 0 rows affected (0.00 sec)
Note that you have to write commit, because if you don't it wont flush it to the database.
来源:https://stackoverflow.com/questions/14347217/how-can-i-update-two-tables-in-one-query