Mysql
 sql >> Base de données >  >> RDS >> Mysql

Deux instructions foreach avec une seule requête MySQL ?

Appliquée à votre cas, voici la réponse de Danny adaptée :

<?php

//first query:
$arrk = array_keys($_POST['overtimehours']);
$arrv = array_values($_POST['overtimehours']);
$id_list = implode(',', $arrk);

$whens = implode(
    "\n    ",
    array_map(
        function ($id, $value) {
            return "WHEN {$id} THEN {$value}";
        },
        $arrk,
        $arrv
    )
);

$sql1 = "
    UPDATE $TABLE
    SET ot_hours = CASE trans_num
    {$whens}
    END,
    ot_status=1, 
    ot_submitdate='$ot_submitdate'
    WHERE id IN ({$id_list})
    AND uid='$contextUser' 
    AND (ot_status=0 OR ot_status=1 OR ot_status=3) 
";

//second query:
$arrk = array_keys($_POST['lieutimehours']);
$arrv = array_values($_POST['lieutimehours']);

$id_list = implode(',', $arrk);

$whens = implode(
    "\n    ",
    array_map(
        function ($id, $value) {
            return "WHEN {$id} THEN {$value}";
        },
        $arrk,
        $arrv
    )
);

$sql2 = "
    UPDATE $TABLE
    SET lieu_hours = CASE trans_num
    {$whens}
    END,
    ot_status=1, 
    ot_submitdate='$ot_submitdate'
    WHERE id IN ({$id_list})
    AND uid='$contextUser' 
    AND (ot_status=0 OR ot_status=1 OR ot_status=3) 
";

//now use pdo to run sql1 and sql2

?>