include("connect.php");
$username = mysql_real_escape_string($_REQUEST[username]);
function updateData($key){
$field = "$$key";
if($field == "") {
} else {
$sql= "UPDATE users SET $key = '$field' WHERE username ='$username'";
mysql_query ( $sql , $conexion );
}
}
updateData('password');
updateData('firstname');
What I’m trying to make is an automatic way for this PHP file to recognize the fields and not save them if the input field value is empty.
If I mannually put the name of the field on the $key spaces, it works, but once I turn it into a function an run it, it doesn’t work.
Don’t write your code like this.
For starters, it’s not readable – it makes whoever is maintaining the code have to go find this function to figure out where the data being used is coming from.
Secondly, you’ll run into issues with variable scope – inside the function, none of your variables are defined unless you reference them with the
globalkeyword to bring them into scope.Instead, write your function like this:
and pass in the relevant values; that’s what function arguments are designed for. You might also want to consider escaping the contents of the arguments before interpolating them.