insert into two tables at the same time with php

Asked

Viewed 490 times

0

I’m in trouble. I have the tables usuario and aluno which are related by primary and foreign key. I want to make an insertion with php to insert data into the two tables, the idusuario table usuario should appear in the field idusuario table aluno. I saw some examples, but it didn’t work and if anyone can help I would be grateful. follow the tables of the bank, the insertion form and the code php to insert which I tried to use. The primary key of usuario connects to the idUsuario table aluno.

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:

student bank 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
}
?>
  • You want to ask the student id entered is this?

  • i want to perform the insertion in the bank. type is a form that has information divided in the two tables. when performing the insertion, the user table must be the same as the student table.

  • At the top of the question there are two links with the solution of the problem, it is the same doubt. If you have any more questions you can notify a user using an arroba before the name e.g.: @rray.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.