Error inserting data into table!

0

In the student master system this logic scheme is available:

HowcanIenterthecorrectstudentdata?

SQL

--GeraçãodeModelofísico--SqlANSI2003-brModelo.CREATETABLEAluno(idalunovarchar(50)PRIMARYKEYauto_increment,nomeAlunovarchar(50),matriculavarchar(50));CREATETABLEEndereco(idenderecovarchar(50)PRIMARYKEY,nomeruavarchar(50),cidadevarchar(50),idalunovarchar(50),FOREIGNKEY(idaluno)REFERENCESAluno(idaluno));CREATETABLETurma(idturmavarchar(50)PRIMARYKEY,codturmavarchar(50),nomeprofessorvarchar(50),quantidadealunosint,idalunovarchar(50),FOREIGNKEY(idaluno)REFERENCESAluno(idaluno));

PHPCode

<?php$NOME="";
        $MATRICULA      ="";
        $NOMERUA        ="";
        $CIDADE         ="";
        $CODTURMA       ="";
        $NOMEPROFESSOR  ="";
        #QUANTIDADE     ="";

     $query = "INSERT INTO aluno('NOME','MATRICULA') VALUES($NOME,$MATRICULA)";

    ?>
    
asked by anonymous 07.10.2017 / 01:32

1 answer

1

First of all I took the liberty of changing its structure, as the field idaluno is AUTO INCREMENTO I believe that it is better to work with numeric type, so I changed to int :

CREATE TABLE Aluno (
  idaluno int PRIMARY KEY AUTO_INCREMENT,
  nomeAluno varchar(50),
  matricula varchar(50)
);

CREATE TABLE Endereco (
  idendereco int PRIMARY KEY AUTO_INCREMENT,
  nomerua varchar(50),
  cidade varchar(50),
  idaluno int,
  FOREIGN KEY(idaluno) REFERENCES Aluno (idaluno)
);

CREATE TABLE Turma (
  idturma int PRIMARY KEY AUTO_INCREMENT,
  codturma varchar(50),
  nomeprofessor varchar(50),
  quantidadealunos int,
  idaluno int,
  FOREIGN KEY(idaluno) REFERENCES Aluno (idaluno)
);

Now let's get down to the problem, you can not put the field names between aspas simples , then your INSERT would look like this:

$query = "INSERT INTO Aluno (nomeAluno, matricula) VALUES('$NOME', '$MATRICULA')";

After this INSERT you need to recover the idaluno that was automatically generated:

$query = "SELECT @@IDENTITY AS id";

And yes, you can do INSERT in the other tables:

$query = "INSERT INTO Endereco (idendereco, nomerua, cidade, idaluno) VALUES('$NOMERUA', '$CIDADE', $IDALUNO)";
$query = "INSERT INTO Turma (codturma, nomeprofessor, quantidadealunos, idaluno VALUES ('$CODTURMA', '$NOMEPROFESSOR', $QUANTIDADE, $IDALUNO)"
    
07.10.2017 / 02:00