I have a small form that is generated from a mysqli->query and I’ve set each inputs name to be an array, such as name="Shift_ID[]". Then I have a for loop that is meant to UPDATE the records one at a time as it loops through. The problem I have is that the $i variable is a different value within the same loop and I don’t understand why. This is my code:
if(isset($_POST['update_submit']))
{
$id = $_POST['Shift_ID'];
$name = $_POST['Shift_Name'];
$short_name = $_POST['Shift_Short_Name'];
$color = $_POST['Shift_Color'];
$shift_total_records = "5";
for($i = 0; $i <= $shift_total_records; $i++)
{
$sql = ("UPDATE shift SET Shift_ID = '$id[$i]', Shift_Name = '$name[$i]', Shift_Short_Name = '$short_name[$i]', Shift_Color = '$color[$i]' WHERE Shift_ID = '$i'");
echo "SQL: " . $sql . "<br>";
if(!$result_shift_update = $mysqli->query($sql))
{
die ('There was an error updating the shift table [' . $mysqli->error . ']');
}
}
}
The echo returns this:
SQL: UPDATE shift SET Shift_ID = '1', Shift_Name = 'Morning', Shift_Short_Name = 'AM', Shift_Color = '#FF0000' WHERE Shift_ID = '0'
I was expecting Shift_ID = '1' and WHERE Shift_ID = '1'. Can someone explain why this is happening? Also, before someone says it, I do know this is open to injection attacks and I need to use prepared statements.
*EDIT: * The reason I had it Shift_ID = '$id[$i]' and WHERE Shift_ID = '$i' was because I wanted to user to be able to change the Shift_ID field if they wanted to. The point would be to have the option to rearrange the order. The Shift_ID is the PRIMARY KEY, so they would get an error if they tried to use the same number twice, but is there a way to make this do what I want?
You’ve used a different variable in each location. Do you mean this: