checking whether a form value has changed upon submit checking whether a form value has changed upon submit codeigniter codeigniter

checking whether a form value has changed upon submit


I haven't used CodeIgniter, but I've certainly done what you're doing in pure PHP-based sites.

I've followed two ways of thinking, in different projects.

Strategy #1: Multiple writes are cheap.

If a user clicks "Submit" rather than "Cancel", they've changed at least one field. So the cost of doing an UPDATE table SET name=%s,email=%s,gender=%s WHERE id=%d isn't much more than a simple UPDATE table SET gender=%s WHERE id=%d. If you're going to the expense of a WHERE and a write, making the write a few extra fields doesn't matter, especially with the frequency that it'll happen.

So: don't worry about it, just update everything with what you get back in the form. If you overwrite a field with the same data, it doesn't matter. When it comes down to it, you want your database to reflect everything that came back in the form, regardless of what was in the db before.

Strategy #2: Use a session variable.

If you've populated the form with current data, you've already likely pulled it into an array. So copy the array into $_SESSION, and compare the fields after the POST.

Strategy 1 is easier to program, but does use slightly more database CPU and bandwidth. Strategy 2 is has slightly less database impact at the expense of quite a bit more CPU used on your web server, and it's more prone to development error.

I still don't know which way is better, but the arguments for both seem valid. These days, I tend to go for whatever solution is the most simple. But I realize that it's easier to scale your web cluster than your database cluster, so if you're developing something that will be very large, it's probably better to put more effort into optimizing things in favour of your database rather than your web servers.

Note that if you're storing your session data in a database instead of temp files, then #2 is actually more costly in terms of database server impact.


You're saying that the users can edit entries from a database, so just send the record id as a hidden input field.

By the time the user submits the form, you retrieve the database record using the hidden field and make the necessary comparisons.

Btw, to prevent users from trying to modify other's records it's advisable to add a checksum to the id field that only you can verify, something that can be done using hash_hmac. Alternatively, you could verify the record ownership if they're logged in.


The only real solution here is knowing the initial value of the form input and then comparing it to the submitted value. You could pass the original value to the browser as a hidden form field and a slightly different name and then compare the two server-side though -- that should net you the desired effect if you don't know what the original value is already.