So I have this basic html form. My goal is to pass the values submitted to this form into a mysql table.
<form action="?action=settings" method="post">
<ul>
<li>
<label for="settingValue[1]">Setting 1:</label>
<input type="text" name="settingValue[1]" id="setting1" required />
</li>
<li>
<label for="settingValue[2]">Setting 2:</label><br>
<input checked type="radio" name="settingValue[2]" value="1" />On<br>
<input type="radio" name="settingValue[2]" value="0" />Off
</li>
<li>
<input type="submit" name="saveChanges" value="Save Changes" />
</li>
</ul>
</form>
My mysql table has only 3 columns (id, settingName, settingValue)
So I want to update multiple records in my table using this form (In this case rows 1 and 2) by storing the value into the “settingValue” column.
After some research I found that what seems to be the best way to do this would be by posting an array (Which is what I attempted to do above), then use a foreach loop to to run through the array and update the table.
I guess my main problem is figuring out how to use the array. Because I need to UPDATE a record NOT create a new one. I also need to retain the ID so I can update the corresponding record.
After hours of googling my best guess was to do this:
if ( isset( $_POST['saveChanges'])) {
foreach($_POST['settingValue'] as $key => $settingValue ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$conn->exec("UPDATE settings SET settingValue=$settingValue WHERE id=$key");
$conn = null;
}
But it is yielding no results.
Keep
$settingValueand$keyin quotes:Tip: Keep
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );outside theforeachloop. No need to repeat the connection on each loop