Link to home
Start Free TrialLog in
Avatar of Patrick Martin
Patrick MartinFlag for United States of America

asked on

PHP / MySQL Update only changed fieds

How can I make this so that it only updates the fields that have changed? For instance if someone gets a new phone number or email address.

Thank you
$Car_Number = $_POST['Car_Number'];
$Driver_Name=$_POST['Driver_Name'];
$Home_Town=$_POST['Home_Town'];
$Cartoon_Character=$_POST['Cartoon_Character'];
$Highlights=$_POST['Highlights'];
$Email=$_POST['Email'];
$Phone=$_POST['Phone'];

$newname = $Car_Number.".JPG";
$foldername = "CarPics";
$Picture = '<img src="'.$foldername."/".$newname. '" width="260" height="195">';
move_uploaded_file($_FILES['mailfile']['tmp_name'], "../$foldername/$newname");
chmod ("../$foldername/$newname", 0644);

$sql = mysql_query("UPDATE Roster SET `Image` = `$Picture`, `Driver_Name` = '$Driver_Name',
        `Home_Town` = '$Home_Town', `Cartoon_Character` = '$Cartoon_Character', `Highlights` = '$Highlights',
        `Email` = '$Email', `Phone` = '$Phone' WHERE `Car_Number` = '$Car_Number'") or die(mysql_error());

Open in new window

Avatar of dockhand
dockhand

I would create some variables to save the original values when you read the customer info and then create your "$sql" statement dynamically.  Something like:

$sql = 'mysql_query("UPDATE Roster SET `Image` = `$Picture`'
If $Origanal_Driver_Name != $Drive_Name {
   $sql &=  "`Driver_Name` = '$Driver_Name'"
}

etc.
UPDATE Roster
SET Image = `$Picture`'
WHERE `Car_Number` = '$Car_Number'
and image != `$Picture`
The only way I can see that updating a field could be a problem is if your form you are submitting doesn't have the same values (blank perhaps) as in the database ... if that is the case you need to check each variable if it is empty first.

IF CHECKING for BLANK VALUES

foreach (array('Car_Number','Driver_Name','Home_Town','Cartoon_Character','Highlights','Email','Phone') as $field) {
      if ($_POST[$field]) { # checks if it has a value
            $sql = mysql_query("UPDATE Roster SET $field='$_POST[$field]'");
      }
}

OR


IF THE same values are in the input variables ... it doesn't matter because the database will look the same whether the update is done or not.  You don't save any time because to check each value if it has changed you'd have to do a query to fetch the current values.
ASKER CERTIFIED SOLUTION
Avatar of ropenner
ropenner
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Patrick Martin

ASKER

ropenner - thank you - How does the where statement fit into that?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial