My objective is to update necessary data using one function instead of having different functions to update different fields. So, I've created one and I think this is not really elegant, efficient or secure. I would seriously like a review if possible.
Key. $data is an array. $data[0] = column to update. $data[1] = new data. $data[2] = username of the user.
Code:
public function handleUserDataUpdate($data) {
if($userMapper->validate($data) === true) {
$userMapper->update($data);
} else {
$errors['count'] = count($errors);
return $errors;
}
}
UserMapper
Class Methods:
public function validate($data) {
switch ($data[0]) {
case 'rank':
if(empty($data[1])) {
$errors[] = "The rank field cannot be empty!";
}
if(count($errors) > 0) {
return $errors;
} else {
return true;
}
break;
case 'display_name':
if(empty($data[1]) || strlen($data[1]) < 3 || strlen($data[1] > 20)) {
$errors[] = "The display name should contain at least 3 to 20 characters";
}
if(count($errors) > 0) {
return $errors;
} else {
return true;
}
break;
}
}
public function update($data) {
$sql = "UPDATE users SET " . $data[0] . "=? WHERE username=?";
$query = $this->db->prepare($this->sql);
$query->bind_param('ss', $data[1], $data[2]);
$query->execute();
$query->close();
}
$sql = "UPDATE users SET " . $data[0] . "=? WHERE username=?";
instead of write" . $data[0] . "
you could use?
. – Marco Acierno Jun 28 at 12:24$sql = "UPDATE users SET ?=? WHERE username=?"; $query->bind_param('sss', $data[0], $data[1], $data[2]);
– CodeX Jun 28 at 12:26