I have searched a lot but can't find my solution. I am new to php so I hope I can explain my question clearly.
I am trying to build a system that allows the user to update his/her information. There are some inputs in the form which are; username, email, old-new password...
What I want to achieve is updating only the changed inputs. (blank inputs will be ignored)
So I want the username input to be checked if it is blank and keep the process working regardless of the result if username is blank or not. By that way ı can update the table with only changed/typed inputs.
How can I achieve that?
if($username != "") {
//update the username
}
// keep process going even if username condition is true.
if($email != "") {
// update the email
}
PS: I didn't write the whole codes because there are at least 10 inputs and 3 selects. I tried lots of nested if,elseif,else statements so the codes I tried is so complicated and long.
I just wonder If there is a way to keep the process going after an "if statement" even if the condition is true.
UPDATE
I tried using just ifs, I was expecting the process will be continue but, for example;if I left blank the username and type the email, it updates the email.But if username input was typed and the email was typed; it just updates the username.
What could be the problem ?
If all the data is updated on a single table say users
, then you can generate the update command on the fly using the input data and finally execute the query as
<?php
$qry_update = "UPDATE `users` SET " ;
if($username != ""){
$qry_update .= "`username` = '$username', ";
}
if($email != ""){
$qry_update .= "`email` = '$email', ";
}
....
....
$qry_update = rtrim($qry_update, ',');
$qry = $qry_update." where idusers = $idusers ";
// Execute the query
?>
The above is conventional way of doing it. But its better to use PDO with bind params.
In PHP
, the code outside your if statement
will be executed.
The example you provided will check both if statements
, and execute the code within if your statement
is true.
So have you tried the following?
if (!empty($username)) {
// Do something to username
}
// Code here will still execute
So here the if statement will run if it is true otherwise it will just skip it.
elseif will have to go after an if and catches a next scenario, but if they need to be run all then don't use elseif
if ($condition) {
// code to run if statement passes
} elseif ($condition) {
// only checks the condition if the first if is not run
} else {
// has no condition but only runs if all above does fail to run
}
// Code here will still run as long as the above does not cancel the script. As Fatals, exit() die() return etc.