I am working on an update query where the values should only update when the value is not null or empty. Now it updates everything regardless the value. Please help me out with this one.
$query = "UPDATE bundels
SET batchkosten = CASE WHEN ". $_POST['batchkosten'] . " IS NOT NULL
THEN ". $_POST['batchkosten'] . "
ELSE batchkosten
END CASE,
CASE WHEN ". $_POST['maandelijkse_kosten'] . " IS NOT NULL
THEN ". $_POST['maandelijkse_kosten'] . "
ELSE maandelijkse_kosten
END CASE,
CASE WHEN ". $_POST['aanmeldkosten'] . " IS NOT NULL
THEN ". $_POST['aanmeldkosten'] . "
ELSE aanmeldkosten
END CASE,
CASE WHEN ". $_POST['transactiekosten'] . " IS NOT NULL
THEN ". $_POST['transactiekosten'] . "
ELSE transactiekosten
END CASE,
CASE WHEN ". $_POST['referral'] . " IS NOT NULL
THEN ". $_POST['referral'] . "
ELSE referral
END CASE,
CASE WHEN ". $_POST['actief'] . " IS NOT NULL
THEN ". $_POST['actief'] . "
ELSE actief
END CASE
WHERE bundel_id = ". $_POST['bundel_id'] . "";
$result = mysql_query($query, $db) or die ('FOUT: werkt niet');
header ("Location: vergelijker_bewerken.php");
} else {
$bundels = mysql_query("SELECT bundels.psp_id, psp.psp_id, psp_naam, bundels.bundel_id, batchkosten, maandelijkse_kosten, aanmeldkosten, transactiekosten, referral, actief from bundels
JOIN psp
ON psp.psp_id = bundels.psp_ID");
}
You can use a case
UPDATE bundels
SET batchkosten = case when ? is not null and length(?) > 0
then ?
else batchkosten
end,
...
Your current query translates to (which should throw an error actually)
UPDATE bundels
SET batchkosten = CASE WHEN ? length(?) > 0
THEN ?
ELSE batchkosten
END
WHERE bundel_id = ?
But use instead:
SET batchkosten = CASE WHEN ? is not null and length(?) > 0
you can write script some like this maybe:
$query = "Update bundels SET ";
$columns = array( "batchkosten",
"maandelijkse_kosten",
"aanmeldkosten",
"transactiekosten",
"referral",
"actief");
foreach($columns as $column){
if(isset($_POST[$column]) && !empty($_POST[$column])){
$query .= $column . " = " $_POST[$column] . " ";
}
}
$query .= " WHERE bundel_id = " . $_POST['bundel_id'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With