2014-06-16 110 views
0

我必须使用PHP的mysql_query()函数在单个查询中执行多个更新查询。 我附加多个更新语句,形成单个查询传递参数到mysql_query()函数。所以最后我得到了一个联合查询,但发现它是错误的。当我在执行期间运行该查询时,我收到错误为“无效查询”。我不明白发生了什么错误,所以请帮助我解决这个问题。我非常痛苦。我已经尽力了。我正在给我的代码参考。如何在PHP中使用MySQL执行多个更新查询?

在这里,我通过查询字符串

越来越可变因素的价值观我querystirng:localhost/ticker/publish-ticker.php?i=1,2,3&j=3,4

if(isset($_GET['i'])) 
{ 
    $selected_tickers = $_GET['i']; 
} 

if(isset($_GET['j'])) 
{ 
    $selected_twitters = $_GET['j'];  
} 

我在这里形成查询

$sql2 = ""; 
if(count($sel_ticker_array) > 0) 
{ 
foreach($sel_ticker_array as $value2) 
{ 
    $tid1 = preg_replace('/[^0-9]/','', $value2);        
    $sql2 .= "update tbl_ticker2 set ticker_flag=0 where id!=$tid1;"; 

} 



foreach($sel_ticker_array as $value) 
{ 
    $tid3 = preg_replace('/[^0-9]/','', $value);         
    $sql2 .= "update tbl_ticker2 set ticker_flag=1,last_used='$todaysdate' where id=$tid3;"; 

} 

} 


if(count($sel_twitter_array) > 0) 
{ 
foreach($sel_twitter_array as $value) 
{ 
    $tid = preg_replace('/[^0-9]/','', $value);        
    $sql2 .= "update tbl_ticker2 set twitter_flag=0 where id!=$tid;"; 

} 



foreach($sel_twitter_array as $value) 
{ 
    $tid = preg_replace('/[^0-9]/','', $value);        
    $sql2 .= "update tbl_ticker2 set twitter_flag=1,last_used='$todaysdate' where id=$tid;"; 

} 
} 

我在这里执行它,但我越来越输出为“无效查询”

$query3 = mysql_query($sql2); 

    if(!$query3) 
    { 
     die("Invalid Delivery"); 
    } 
    else 
    { 
     echo '<script>'; 
     echo 'alert("Ticker Updated Successfully");'; 
     echo 'location.href="add_ticker.php"'; 
     echo '</script>';   

    } 

请帮帮我。

+1

让我知道“您应该使用pdo或mysqli” – Dave

+1

您无法使用'mysql_query'在单个调用中运行多个查询。如果你想这样做,你需要使用'mysqli_multi_query()'。 – andrewsi

+0

你可能想看看如何使用SQL的“IN”语句,如'update tbl_ticker2 set twitter_flag = 1,last_used ='$ todaysdate'其中id在($ tid1,$ tid2,$ tid3);'然后看一看在您的foreach语句构建匹配语句的条件列表 – Dave

回答

0

,你不能将它用于多个查询手册状态。

http://php.net/manual/en/function.mysql-query.php

您可以使用库MySQLi或PDO这一点。

+0

我知道使用mysqli是可能的,但我不知道使用PDO是可能的 - 你有链接吗? – andrewsi

+0

你可以检查这个答案:http://stackoverflow.com/a/6461110/1108700 – mayy00

+0

谢谢你,这很有趣! – andrewsi

相关问题