Is there a better way to clean up the data before insert/update, what I mean by clean up is: if the posted value is blank (or composed of many spaces) then insert null,
I noticed some other php frameworks, they do that automatically, if the value is blank (or many spaces) it's automatically considered like null value and insert/update like null,
In my case: I'm thinking maybe to create a helper (see below) that do this for me but I'm not sure if CodeIgniter already has something already exist.
What I noticed too is: if the value contains space at the right it is not trimmed, unless you add trim function to every posted value
PHP Code:
public function update_social_infos() {
$response = [];
$userModel = new UserModel();
$user = $userModel->find(session()->get('id'));
$rules = [
'facebook' => [
'label' => 'Facebook',
'rules' => 'permit_empty|min_length[3]|max_length[100]'
],
'twitter' => [
'label' => 'Twitter',
'rules' => 'permit_empty|min_length[3]|max_length[100]'
]
];
if (!$this->validate($rules)) {
$response = ['type' => 'error', 'message' => $this->validator->getErrors()];
}
else {
$data = [
'facebook' => empty(trim($this->request->getVar('facebook'))) ? null : $this->request->getVar('facebook'),
'twitter' => empty(trim($this->request->getVar('twitter')) ? null : $this->request->getVar('twitter'),
];
$userModel->update($user['id'], $data);
$response = ['type' => 'success', 'message' => 'Information updated successfully.')];
}
return $this->response->setJSON($response);
}
my helper function to convert empty strings to NULL
PHP Code:
function empty2null($value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = empty2null($v);
}
}
else {
$value = (trim($value) === '') ? null : trim($value);
}
return $value;
}
Then use something like this:
PHP Code:
$data = [
'facebook' => empty2null($this->request->getVar('facebook')),
'twitter' => empty2null($this->request->getVar('twitter')),
];
$userModel->update($user['id'], $data);
Thank you!