I have a considerably big table in my database, and I want to have a function that, for example, performs an UPDATE query.
What I used to do in my older projects was passing all the values for all the columns, and insert them in the query string, like this example:
function updateUser($id, $name, $username){
$query = "UPDATE user SET name = '{$name}', username = '{$username}' WHERE id = '{$id}' ";
return mysqli_query($this->conn, $query);
}
That meaning, every column was being altered even those that weren't changed.
But, this time being a big table, I don't want to sacrifice the application speed.
What I'm trying to do is make some comparisons, therefore optimizing the query, and only then sending it to the database.
Staying in the UPDATE query example from before, this is kind of what I want to do:
function updateUser($old_user, $new_user, $user_id){
$changed = false;
$oldFirstName = $old_user->getFirstName();
$newFirstName = $new_user->getFirstName();
if($oldFirstName == $newFirstName){
$firstNameQuery = "";
}else{
$firstNameQuery = " first_name = '".mysqli_escape_string($this->conn, $newFirstName)."',";
$changed = true;
}
$oldLastName = $old_user->getLastName();
$newLastName = $new_user->getLastName();
if($oldLastName == $newLastName){
$lastNameQuery = "";
}else{
$lastNameQuery = " last_name = '".mysqli_escape_string($this->conn, $newLastName)."',";
$changed = true;
}
$oldEmail = $old_user->getEmail();
$newEmail = $new_user->getEmail();
if($oldEmail == $newEmail){
$emailQuery = "";
}else{
$emailQuery = " email = '".mysqli_escape_string($this->conn, $newEmail)."',";
$changed = true;
}
if($changed){
$query = "UPDATE user SET {$firstNameQuery}{$lastNameQuery}{$emailQuery} WHERE user_id = {$user_id}";
return mysqli_query($this->conn, $query);
}else{
return 0;
}
}
Although, as you can see, as the table grows this function gets bigger and with a lot more comparisons and attributions.
My question is: Am I saving a noticeable amount of time doing this, or it isn't whorth it?