I'm in trouble. I have the usuario
and aluno
tables that are related by primary and foreign key. I want to make an insert with php
to insert data into the two tables, and the idusuario
of the usuario
table should appear in the idusuario
field of the aluno
table. I saw some examples, but it did not work and if anyone could help, I would be grateful. follows the tables of the bank, the insertion form and the code php
to insert that I tried to use. The primary key of usuario
binds to idUsuario
of the aluno
table.
CREATE TABLE aluno (
idAluno int(11) NOT NULL,
semestre int(50) NOT NULL,
curso varchar(200) NOT NULL,
idUsuario int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE usuario (
idusuario int(11) NOT NULL,
nome varchar(200) NOT NULL,
campus varchar(200) NOT NULL,
sexo varchar(200) NOT NULL,
email varchar(200) NOT NULL,
senha varchar(200) NOT NULL,
tipoUsuario varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What I've done so far:
bank-student table
function insereAluno($conexao, $nome, $campus, $sexo, $email, $senha, $tipoUsuario, $semestre, $curso) {
$query = "insert into usuario(nome, campus, sexo, email, senha, tipoUsuario) values ('{$nome}', '{$campus}', '{$sexo}', '{$email}', '{$senha}', '{$tipoUsuario}')";
$query = "insert into aluno (semestre, curso, idUsuario) values ('{semestre}', '{curso}', (select LAST_INSERT_ID(idUsuario)))";
return mysqli_query($conexao, $query);
}
add-student table
$nome = $_POST['nome'];
$campus = $_POST['campus'];
$sexo = $_POST['sexo'];
$email = $_POST['email'];
$senha = $_POST['senha'];
$tipoUsuario = $_POST['tipoUsuario'];
$semestre = $_POST['semestre'];
$curso = $_POST['curso'];
if(insereAluno($conexao, $nome, $campus, $sexo, $email, $senha, $tipoUsuario, $semestre, $curso)) { ?>
<p class="alert">O Aluno <?= $nome ?>, do <?= $semestre ?> semestre foi adicionado. </p>
<?php } else {
$msg = mysqli_error($conexao);
?>
<p class="text-danger">O Aluno <?= $nome ?> não foi adicionado: <?= $msg?> </p>
<?php
}
?>