简体   繁体   中英

Two arrays in one SQL query

Consider the following : I have several arrays (let's say 2), that I get with post, like that :

$_POST['date-pack'] :
$date_pack array {
[0] ==> "Juillet 2012"
[1] ==> "Avril 2012"
...

And with this array, I have another one with the id's in the same order as the dates :

$_POST['id_pack'] :
$id_pack array {
[0] ==> "6"
[1] ==> "8"
...

The thing is, I want to update a table, like that :

"UPDATE my_table 
SET date_service = *the_first_date_in_array*
WHERE id_service = *the first_id_in_array*"

and then do the same thing for all the elements in my arrays (they'll have the same number of elements).

I don't know if it's possible to use "foreach" with several arrays and put my query into the loop ... ?

Thanks in advance for your help !

You can try this:

<?php

foreach($_POST['date_pack'] as $k => $date) {
ExecuteQuery("UPDATE my_table SET date_service = " . $date . "
          WHERE id_service = ". $_POST['id_pack'][$k]);
}

Why not use something like:

if(is_array($_POST['date_pack'])
{
    for($i=0;$i<count($_POST['date_pack'];$i++)
    {
    $sql='
    UPDATE my_table 
    SET date_service = '.$_POST['date_pack'][$i].'
    WHERE 
        id_service = '.$_POST['id_pack'][$i].'
        -- and your other conditions....
    ';
    }
}
else
{
    $sql='
    UPDATE my_table 
    SET date_service = '.$_POST['date_pack'].'
    WHERE 
        id_service = '.$_POST['id_pack'].'
        -- and your other conditions....
    ';
}

considering $date_pack & $id_pack are 2 arrays

for($i=0;$i<count($date_pack);$i++)
{
  $the_first_date_in_array = $date_pack[$i];
  $the_first_id_in_array = $id_pack[$i];
  $query = mysql_query("UPDATE my_table 
   SET date_service = ".$the_first_date_in_array."
   WHERE id_service = ".$the_first_id_in_array.");
}

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