Joaquín
Joaquín

Reputation: 19

if - else in multiple update in one query

I have an issue with this query:

foreach ($_POST['cod'] as $i => $cod) {
    $sth = $conn->prepare("UPDATE LPRODALMACEN SET `existencia` = `existencia` + :comprado WHERE `cod` = :cod");
    $sth->bindParam(':comprado', $tExiste[$i]);
    $sth->bindParam(':cod', $_POST['cod'][$i]);
    $sth->execute();
    $i++;
}

I need make an if - else if the condition is 1 or 0, with this:

$_POST['medida'][$i] == '0' ? $_POST['comprado'][$i] : $_POST['tExiste'][$i];

How can I put inside of the query if the $medida is == 0 add the value from $comprado or if medida is == 1 the value from $tExiste?

Upvotes: 0

Views: 35

Answers (1)

Barmar
Barmar

Reputation: 780871

Set a variable based on the condition.

Also, you don't need to use prepare() and bindParam() in the loop. You prepare and bind once, then execute in the loop. bindParam() binds to references, so you just update the variables in the loop.

$sth = $conn->prepare("UPDATE LPRODALMACEN SET `existencia` = `existencia` + :comprado WHERE `cod` = :cod");
$sth->bindParam(":comprado", $comprado);
$sth->bindParam(":cod", $cod);
foreach ($_POST['cod'] as $i => $cod) {
    $comprado = $_POST['medida'][$i] == '0' ? $_POST['comprado'][$i] : $_POST['tExiste'][$i];
    $sth->execute();
}

Upvotes: 1

Related Questions