简体   繁体   中英

how to execute multiple update queries in PHP using MySQL?

I have to execute multiple update queries in single query using mysql_query() funciton of PHP. I append multiple update statements to form single query to pass parameter to mysql_query() function. So at the end I am getting one combined query but it is found to be wrong. When I run that query at that time during execution I am getting error as "Invalid query". I do not understand what is wrong happening , so please help me in this quetion . I am suffering from it so badly. I tried my best. I am giving my code for reference.

Here I am getting values of varibles through querystring

my 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'];    
}  

Here I am forming the query

$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;";

}
}

Here I am executing it but I am getting output as "Invalid query"

$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>';         

    }

Please help me.

You can't do that using the regular mysql-api in PHP.

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.

it can be done using mysqli and the mysqli_multi_query() function.

also read :

Manual states that you cannot use it for multiple queries.

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

You can use mysqli or pdo for this.

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