Forum Moderators: coopster
I've written a foreach loop that will do this, however the $_POST array contains a field/value pair for the submit button and there isn't a column in the table to store this (as it's not required). When the update SQL runs, I get an error that the column doesn't exist.
Can anyone tell me if there is a way that I can either change the form so that the submit value is not in the $_POST array, or change the update SQL so that it doesn't try to updated the submit value.
Here's the form code:
<form class="cssform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Edit the Opening Times:</p>
<table class="open">
<caption><input type="text" name="tab_name" value="<?php echo $caption; ?>"/></caption>
<thead>
<tr class="odd">
<th scope="col">Day</th><th scope="col">Bar Opening</th>
<th scope="col">Kitchen Times * See below</th>
</tr>
</thead>
<tbody>
<?php
//Display each day of the week and opening times$id = $_GET['id'];
$opening = @mysql_query("SELECT o_id, weekday, bar_times, kitch_times FROM openingtimes WHERE t_id = '$id' ORDER BY o_id");
if (!$opening) {
exit ('<p>Error retrieving Opening Times: ' . mysql_error() . '</p>');
}while ($row = mysql_fetch_array($opening)) {
$day = $row['weekday'];
$bartimes = $row['bar_times'];
$kitchtimes = $row['kitch_times'];
$rid = $row['o_id'];
echo "<tr>
<td class='col1'><p><input type='text' name='weekday' value='$day'/></p></td><td class='col2'><p><input type='text' name='bar_times' value='$bartimes'/></p></td>
<td><p><input type='text' name='kitch_times' value='$kitchtimes'/></p></td>
<input type='hidden' name='r_id' value='$rid'/></label></tr>";
}
?>
</tbody>
</table><input type="hidden" name="t_id" value="<?php echo $tid; ?>"/></label>
<div id="formbuttons">
<button type="submit" name="submit" value="submit">Save Changes</button>
</div> <!--formbuttons--></form>
And here's the foreach loop:
$day = $_POST['weekday'];
$bartimes = $_POST['bar_times'];
$kitchtimes = $_POST['kitch_times'];
$tabname = $_POST['tab_name'];
$rid = $_POST['r_id'];
$tabid = $_POST['t_id'];foreach($_POST as $field => $value) {
$sql = "UPDATE openingtimes SET
$field = $value
WHERE o_id='$rid'
AND t_id='$tabid'";
}if (@mysql_query($sql)) {
echo '<p>Your changes have been saved.</p>';
} else {
echo '<p>Error editing the Details: ' .
mysql_error() . '</p>';
}
But the way you've structured your for loop, only the last field in the form will get updated; the $sql statement gets overwritten on each pass. Restructure it so that the pairs get appended and you wind up with:
UPDATE openingtimes SET
$field1 = $value1,
$field2 = $value2,
$field3 = $value3,
.
.
WHERE o_id='$rid'
AND t_id='$tabid'
You're also wide open to sql injection attack - unless this form can only be submitted on your local machine, you should check the submitted values to make sure they're all valid and safe, by at the very least running them through mysql_real_escape_string [us2.php.net].