Updating necessary data using just one function 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-&gt;validate($data) === true) {
        $userMapper-&gt;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) &gt; 0) {
                return $errors;
            } else { 
                return true;
            }
            break;
        case 'display_name':
            if(empty($data[1]) || strlen($data[1]) &lt; 3 || strlen($data[1] &gt; 20)) {
                $errors[] = "The display name should contain at least 3 to 20 characters";
            }
            if(count($errors) &gt; 0) {
                return $errors;
            } else {
                return true;
            }
            break;
    }
}
public function update($data) {
    $sql = "UPDATE users SET " . $data[0] . "=? WHERE username=?";
    $query = $this-&gt;db-&gt;prepare($this-&gt;sql);
    $query-&gt;bind_param('ss', $data[1], $data[2]);
    $query-&gt;execute();
    $query-&gt;close();
}
You are vulnerable to SQL Injections. Even when you are using Prepared statements, doing It wrong will kill you.


$sql = "UPDATE users SET " . $data[0] . "=? WHERE username=?";



This makes you exposed to SQL injections because your function is not private. You should not allow "user" access to "critical" functions. make that function private and you should be good to go.

As soon as the user is allowed to set $data[0] you're screwed.