I have following PHP loop + SQL Update query.
for ($i=0;$i<count($_POST['id']);$i++) {
if(!isset($_POST['live'][$i])){
$_POST['live'][$i] = "0";
} else { $_POST['live'][$i] = "1"; }
$id = ($_POST['id'][$i]);
$live = ($_POST['live'][$i]);
$usr2 = $_SESSION['usr'];
$updated = date("F j, Y, g:i a",time()+60*60);
$sql = "UPDATE news SET live = '$live', usr2 = '$usr2', updated = '$updated' WHERE id = $id";
$result = mysql_query($sql);
//echo $sql."<br />";
}
if($result) {
header("location: notes.php");
exit();
}else {
die("Query failed");
}
How does it work:
- I’m submitting big form will ALL OF THE table rows.
- receiving this in different file as an array
- if
$_POST['live']is ‘not set’ – set it to ‘0’, if ‘set’ set it to 1 - update array data within for loop
How to UPDATE only the rows which have been actually been changed?
Those which value from $_POST[‘live’] is actually different from this saved in DB, as the condition would be change of our $live row.
I guess you’re concerned about the
updatedfield and that this value only changes when something has been altered. (If that’s not the case forget about this answer.)You can define an
ON UPDATE CURRENT_TIMESTAMPclause for a timestamp field. Each time a record is updated without explicitly setting a value for this field mysql uses the current time as its new value……but only if the record is altered; if you “update” the fields with the same value as are already in that record nothing happens.
demo script:
prints
As you can see as a result of the first update query the timestamp field has been updated while the second query setting new=old didn’t affect the
updatedfield.