Page 1 of 1
Update Database only if what entered in $_POST is different?
Posted: Mon Nov 16, 2009 9:11 pm
by Karalius
Hello Everyone

First Post/Question:
I have a database with information. There are 2 parts to my form. One is name, another is Lastname.
I'm learning codes, so this is for learning purposes.
I would like to know, how can I make php check if what I entered is different from what's in the database?
My ideal operation would be:
Check if "name" is different from "name" (in database), then update database for name. BUT it shouldn't touch Lastname. and Vice Versa.
Re: Update Database only if what entered in $_POST is different?
Posted: Mon Nov 16, 2009 11:13 pm
by califdon
Welcome to the forum. There are 2 answers to your question. The first is, why would you ever want to do that? If the point is to update the table, you would normally just update it, regardless of whether it is the same as the previous data. This requires less operations to the database. The difference only matters when you have millions of transactions a day, but there are many databases that do have that much traffic, so it doesn't make any sense for you to learn how to do something that is not normally done. Learn how to do the things that
are done, in practice.
But to answer your question directly, yes, of course you could perform a SELECT query to determine what data is currently stored, compare it with what you have received via $_POST or any other way, and only perform an UPDATE query if they are different. But, as I said, what would be the point? You wouldn't be saving anything in terms of operations on the database, since you would always be performing at least one query, and sometimes two. As to affecting other fields in the table, you only update the fields you want, not all the fields. If you are not familiar with the syntax of an UPDATE query, read this:
http://www.tizag.com/mysqlTutorial/mysqlupdate.php
Re: Update Database only if what entered in $_POST is different?
Posted: Tue Nov 17, 2009 1:53 am
by Karalius
Thanks for your reply and welcome!
Alright understood. I'm using Zend Frameworks and whenever I submit my form without editing BOTH of the text areas, I receive a blank page, a sign that something is wrong. When I edit both, it submits fine..
I'm a newbie that decided he'd start on Zend Frameworks... some say stupid move but that's just me

Re: Update Database only if what entered in $_POST is different?
Posted: Tue Nov 17, 2009 2:07 am
by iankent
Without seeing your code its hard to say, but if you run an UPDATE query where no values change then no rows will be updated, so if your code is checking to see whether any rows have been updated (e.g. mysql_affected_rows()), it'll return 0 if nothing has been changed.
If you want to check if the query was successful you need to check for errors (mysql_error()) rather than checking for updated rows