I am making a function that is responsible for saving the data of a form in two databases, the first called users and the second company.
I explain its operation as it would be, when we create a user in the form when pressing save if everything is correct the data is saved in the users table and the text for the company name goes to another table also called company, on the contrary if everything is correct but the company name already exists in the database we will only save the new user data.
public function guardar()
{
helper('text');
$users = new UserModel();
$modelEnterprise = new EmpresaModel();
$validacion = $this->validate([
'name' => 'required|min_length[3]|max_length[20]',
'surname' => 'required|min_length[3]|max_length[50]',
'enterprise' => 'required|min_length[3]|max_length[50]',
'nif' => 'required|min_length[3]|max_length[9]|regex_match[/^([a-z]|[A-Z]|[0-9])[0-9]{7}([a-z]|[A-Z]|[0-9])$/]',
'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[users.user_email]',
'password' => 'required|min_length[6]|max_length[200]',
'confpassword' => 'matches[password]'
]);
if (!$validacion) {
$session = session();
$session->setFlashdata('mensaje', 'Por favor, revise la información');
return redirect()->back()->withInput();
} else {
$datos = [
'user_name' => $this->request->getVar('name'),
'user_surname' => $this->request->getVar('surname'),
'user_enterprise' => $this->request->getVar('enterprise'),
'user_nif' => $this->request->getVar('nif'),
'user_email' => $this->request->getVar('email'),
'id_rol' => $this->request->getVar('id_rol'),
'user_accept' => $this->request->getVar('user_accept'),
'user_password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
];
$dataE = [
'nombre_empresa' => $this->request->getVar('enterprise'),
];
$db = \Config\Database::connect();
$builder = $db->table('empresa');
$empresas = $builder->select('nombre_empresa');
if($empresas == $dataE){
//guardamos los datos de usuario en la tabla users
$users->insert($datos);
}else{
//guardamos la empresa en la tabla empresa
$modelEnterprise->insert($dataE);
//guardamos los datos de usuario en la tabla users
$users->insert($datos);
}
}
return $this->response->redirect(site_url('/admin/usersList'));
}
Although for some reason I can't find the right condition to check if this entry already exists.
I don't use codeIgniter, but looking at its documentation , it looks like with this line:
you just define the query, so what you may need to do is this instead:
to obtain the result of it and store it in the variable $companies in the form of an associative array, thanks to getResultArray() .
Then, assuming that this new line returns an associative array with the company names, what you must modify is the following line:
for this other one:
where we use the in_array() function to detect if that company name already exists in the values (thanks to array_values() ) of the associative array of $companies.