I want to do more than one database queries in the same file:
Create a user, select the UID of that newly created user, and assign to that same user a specific role.
After I get the UID from the newly created user I save that value into the $userID
variable, but at the end of the file, the variable value gets lost.
Why? (PS: I'm not taking into account security at the moment).
//Create User
$email = strip_tags($_POST['email']);
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
('$email')";
$insertarBase = mysqli_query($conectar,$query);
mysqli_close($conectar);
//look for the UID of the newly created user
$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarUsuario = "SELECT userID, userEmail
FROM usuarios
WHERE userEmail='$email'
";
$resultadoBusqueda = mysqli_query($conectar2,$buscarUsuario);
$row = mysqli_fetch_array($resultadoBusqueda);
$userID = $row['userID'];
mysqli_close($conectar2);
//assign a role to the newly created user
$conectar3 = mysqli_connect(HOST, USER, PASS, DATABASE);
$asignarRol = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
('$userID', 'registered')
";
$asignarRolenBase = mysqli_query($conectar3,$asignarRol);
mysqli_close($conectar3);
echo $userID; //Here the content of $userID is gone, nothing gets printed out
Edited:
For some weird reason, $userID = mysqli_insert_id($conectar);
returns zero.
The creation of the usuarios table statement is this:
CREATE TABLE usuarios(
userID int unsigned not null auto_increment primary key,
userEmail char(50) not null);
Also, echo $asignarRol;
returns:
INSERT INTO rolesUsuarios (userID, nombreRol) VALUES ('0', 'noAutorizado')