在一个查询中更新两个不同的表

时间:2013-08-30 20:03:44

标签: php database

好的,所以我需要在页面加载时更新两个表。其中包含代码:

<?php include'connects.php';
 //Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
 $ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}

$ip = ip2long($ip);

mysqli_query($con,"INSERT INTO visits (ip_adress) VALUES ('$ip') ON DUPLICATE KEY                                                                                 
UPDATE         visit = visit + 1");

mysqli_query($con,"UPDATE ip_visits SET total_visits = total_visits + 1");

mysqli_close($con);
?>

现在我有第二个表需要执行与此顶级表相同的功能:

 mysqli_query($con,"INSERT INTO indVisits (ip_adress) VALUES ('$ip') ON DUPLICATE KEY  
 UPDATE visits = visits + 1");

 mysqli_query($con,"UPDATE totalVisits SET visit = visit + 1");

2 个答案:

答案 0 :(得分:1)

您可以使用mysqli multiquery:http://php.net/manual/en/mysqli.multi-query.php

如果需要在两个不同的表中存储相同的元组,还应考虑重新考虑数据库的设计。

答案 1 :(得分:0)

你可以做这样的事情

mysqli_query($con,"INSERT INTO visits (ip_adress) VALUES ('$ip') ON DUPLICATE KEY                                                                                
UPDATE         visit = visit + 1; 
UPDATE ip_visits SET total_visits = total_visits + 1");

查询字符串中的分号将结束一个查询并发出另一个查询的开头。你不必进行2次单独的通话,只需要一次。