Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Zwei foreach-Anweisungen mit nur einer MySQL-Abfrage?

Auf Ihren Fall angewendet, hier die angepasste Antwort von Danny :

<?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

?>