I have a query regarding database and forms in PHP:
I have the following users table
CREATE TABLE IF NOT EXISTS `login`.`usuarios` (
`nombres` VARCHAR(30) NULL,
`apellidos` VARCHAR(30) NULL,
`cedula` VARCHAR(13) NOT NULL,
`telefono` VARCHAR(15) NULL,
`direccion` VARCHAR(45) NULL,
`sexo` VARCHAR(10) NULL,
`sesion_id` INT(10) NOT NULL,
PRIMARY KEY (`cedula`),
INDEX `fk_usuarios_sesion_idx` (`sesion_id` ASC),
CONSTRAINT `fk_usuarios_sesion`
FOREIGN KEY (`sesion_id`)
REFERENCES `login`.`sesion` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
And I have the session table
CREATE TABLE IF NOT EXISTS `login`.`sesion` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`correo` VARCHAR(45) NULL,
`usuario` VARCHAR(10) NULL,
`password` VARCHAR(100) NULL,
`last_session` DATETIME NULL,
`activacion` INT NULL,
`token` VARCHAR(40) NULL,
`token_password` VARCHAR(100) NULL,
`password_request` INT(11) NULL,
`id_tipo` INT(11) NULL,
`estatus` INT(2) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
They are related to each other from 1 to 1. The main session key is as a foreign key in users.
In PHP I have a form for users to register on my system. Everything is inserted normal in the tables but I only have one problem, because if in the sesions table the ID is autoincrement because being itself foreign in users is not filled too?
At this point I have already registered several users on my system, and everything inserts well, but the foreign key is always empty, it is not associated with the number that is assigned autoincrement in sessions.
To insert I do it in the following way:
function registraUsuario($nombres, $apellidos, $cedula, $telefono, $direccion, $sexo){
global $mysqli;
$stmtr= $mysqli->prepare("INSERT INTO usuarios (nombres, apellidos, cedula, telefono, direccion, sexo) VALUES(?,?,?,?,?,?)");
$stmtr->bind_param('ssssss', $nombres, $apellidos, $cedula, $telefono, $direccion, $sexo);
if ($stmtr->execute()){
return true;
} else {
return 0;
}
}
function registraSesion($email, $usuario, $pass_hash, $activo, $token, $tipo_usuario, $estatus){
global $mysqli;
$stmt = $mysqli->prepare("INSERT INTO sesion (correo, usuario, password, activacion, token, id_tipo, estatus) VALUES(?,?,?,?,?,?,?)");
$stmt->bind_param('sssisii', $email, $usuario, $pass_hash, $activo, $token, $tipo_usuario, $estatus);
if ($stmt->execute()){
return $mysqli->insert_id;
} else {
return 0;
}
}
Additional I must say that I have the foreign key as NULL because if I do not put it NULL, simply the data that registers for users (names, surnames, dni ..) are not registered ... but being NULL if everything is registered without inconveniences except The foreign key.
Please, if you can help me with this problem I have, or if you can tell me how I can do or what I am doing wrong?