note 38712 deleted from function.array-diff-assoc by nlopess
| From: | nlopess@php.net | Date: | Sun, 04 Jan 2004 11:52:14 +0000 |
| Subject: | note 38712 deleted from function.array-diff-assoc by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-62894@lists.php.net to get a copy of this message | ||
Note Submitter: melker@jazzfree.com
----
This code uses array_diff_assoc() to automatically update a MySQL table through a form that has
elements with *the same fieldnames* as the db fields, by comparing the $_POST array to the
mysql_fetch_assoc() array of the selected db row. Of course this code could be improved with
security checks, variable type checks etc but for me it does the thing :D
/* define or import db connection values $database and $connection first */
mysql_select_db($database, $connection);
$id = (isset ($_GET['Id'])) ? $_GET['Id'] : ((isset ($_POST['Id'])) ?
$_POST['Id'] : -1); /* get the row identifier, you may have different needs */
$query_RS_member = 'SELECT * FROM members WHERE Id ='.$id; /* select the db row in initial
state */
$RS_member = mysql_query($query_RS_member, $connection) or die(mysql_error());
$row_RS_member = mysql_fetch_assoc($RS_member);
if ($_POST['Submit']) { /* if form was submitted, go ahead and update */
$diffarr = array_diff_assoc($_POST, $row_RS_member); /* get array of unmatching keys => values
between $_POST array and db row array $row_RS_member */
foreach ($diffarr as $key => $value) {
if ($key!='Submit') { /* don't compare 'Submit', it's just part of
the form mechanism */
$updatevalues.= $key.'="'.$value.'" , '; /* construct the
querystring component, only changed values are added to the query */
}
}
if ($updatevalues) { /* if no changes were made in the form, the update would not execute */
$updatesql = 'UPDATE members SET '.substr($updatevalues,0,-2).'WHERE Id='.$id;
/* substr is for stripping off the last comma from $updatevalues string here */
mysql_select_db($database, $connection);
$updateresult = mysql_query($updatesql, $connection) or die(mysql_error()); /* update row */
$query_RS_member = 'SELECT * FROM members WHERE Id ='.$id; /* get the updated row */
$RS_member = mysql_query($query_RS_member, $connJack) or die(mysql_error());
$row_RS_member = mysql_fetch_assoc($RS_member);
//echo $updatesql; /* just for tweaking */
}
}
/*
HTML form with fieldnames matching the table fields, e.g.
<input name="Name" type="text" id="Name" value="<?php echo
$row_RS_member['Name'] ?>">
Field value should default to db value, as in the example!
*/