I'm using a rather long HTML form to update lots of details relating to a product - for brevity I won't share the form in its entirety. However, for illustrative purposes here's a snippet :
HTML FORM
<form name="form1" method="post" action="update_ac.php">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<input name="season" type="text" class="button_select" id="season" value="<?=$rows['season']; ?>" size="10" />
<input name="restock" type="checkbox" id="restock" value="on" <?php if($rows['restock']=='on') { echo 'checked="checked"'; } ?>/>
// other fields
</td>
</tr>
</table>
</form>
My question is when posting the form to update_ac.php
- how can I dynamically generate a MYSQL update statement based on the fields that are completed?
Here's an example of my form action page:
PHP FORM Action
<?php
foreach ($_POST as $key => $value) {
$$key = $value;
}
$sql= mysql_query ("
UPDATE product SET
title='".$title."',
rating='".$rating."',
season='".$season."',
brand_id='".$brand_id."',
category='".$category."',
... etc ");
?>
I don't want to have to declare every single field that could possibly need updating in the UPDATE statement. I would like the UPDATE statement to only address the fields concerned given the presence of defined PHP variables posted from the form.
At the moment, I'm getting lots of NOTICE: Undefined variable x
where there have been empty fields when posting the form.
I hope this makes sense - little long winded.
Any advice? Thanks
UPDATE
Following on from @Styphon's answer - I amended it slightly to include the WHERE
condition at the end of the query.
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
if( ! empty($val)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$product_id = $_POST['product_id'];
$query = $query . "WHERE product_id = '".$product_id."' ";