I want to update multiple rows with multiple wheres. When i update only 1 input field it works perfecly, but when i update diffrent weeks and field the query fails. I dont know how to put this code togetter. I already search on google and stackoverflow but could not find something that fits my question.
here is my code
if(isset($_POST["opslaan"]))
{
unset($_POST["opslaan"]);
foreach($_POST as $input => $inner_arr)
{
foreach($inner_arr as $week => $value)
{
$update_query[] = $input." = '".$value."' WHERE week = ".$week;
}
}
$test = implode(", ", $update_query);
echo $test;
if(mysqli_query($conn, "UPDATE buitenklimaat SET ".$test))
{
header("location: dashboard.php?user=1&page=gewasregistratie");
echo "done";
}
else
{
echo "Failed !";
}
}
echo output:
gem_buitentemperatuur_etmaal = '1' WHERE week = 1,
gem_buitentemperatuur_etmaal = '2' WHERE week = 2,
gem_buitentemperatuur_etmaal = '3' WHERE week = 3
$query = "UPDATE buitenklimaat SET ";
foreach($_POST as $input => $inner_arr)
{
$query .= $input.' = CASE ';
foreach($inner_arr as $week => $value)
{
$query .= ' WHEN week = '.$week. ' THEN '.$value;
}
$query .= ' ELSE '.$input.' END , ';
}
$query = rtrim($query, ', ');
Not tested, can you see what $query outputs?
Update: Added $input_array
Update 2: Trimming the last comma
Update 3: Restructured loop
You can not update multiple fields like that.
Look at answers in this question SQL Statement with multiple SET's and WHERE's
Also do not forget to sanitize your input, taking values directly from $_POST and putting them into a query is asking for a SQL Injection.
you are trying to do
update
set
where
where
where
which is wrong.
An update query can have only one where
clause.
Update
set //can have multiple set clause
where//only one where clause
now what you can do is:
foreach($_POST as $input => $inner_arr)
{
foreach($inner_arr as $week => $value)
{
$update_query[] = $input." = '".$value."' WHERE week = ".$week;
$test = implode(", ", $update_query);
if(mysqli_query($conn, "UPDATE buitenklimaat SET ".$test))
{
header("location: dashboard.php?user=1&page=gewasregistratie");
echo "done";
}
else
{
echo "Failed !";
}
}
}
You are creating query wrong. Traditional way to perform multiple updates is to create multiple update query in a single string and execute them in one go like as follow
UPDATE buitenklimaat SET Category_ID = 10 WHERE week = 2;
UPDATE buitenklimaat SET Category_ID = 9 WHERE week = 3;
UPDATE buitenklimaat SET Category_ID = 12 WHERE week = 4;
UPDATE buitenklimaat SET Category_ID = 11 WHERE week = 5;
Or there is another way describe by Karl Rixon
UPDATE buitenklimaat
SET Category_ID = CASE week
WHEN 2 THEN 10
WHEN 3 THEN 9
WHEN 4 THEN 12
WHEN 5 THEN 11
ELSE Category_ID
END
You can read further about it through following link
Instead of WHERE
, you could write AND
and put the WHERE
in the UPDATE
string before the test variable, where you'll have all the requisites