Insert data into related tables using PDO

1

Hello, I have 2 tables with a foreign key, I need to insert data into it using the PDO library. OBS: I'm newbie so do not get heavy ..

Tables:

FormCode:

<?phprequire'connect.php';?><html><head><title>CadastrodeCursos</title><metacharset="UTF-8"/>
</head>
<body> 
     <form name="entrar" method="post" action="addinfo.php">
    <h2>Dados do Curso</h2></br>
    <h4>Cursos</h4>
    <select name="curso" id="curso">
        <option hidden selected>Selecione o Curso</option>
        <option disabled>::|Cursos Superiores Tradicionais|::</option>
        <option>Administracao</option>
        <option>Arq e Urbanismo</option>
        <option>Biomedicina</option>
        <option>Ciecias Biologicas</option>
        <option>Ciencia da Computacao</option>
        <option>Ciencias Contabeis</option>
        <option>Prop.e Public. e Jornalismo</option>
        <option>Direito</option>
        <option>Educaçao Fisica</option>
        <option>Enfermagem</option>
        <option>Engenharia Basica</option>
        <option>Engenharias</option>
        <option>Estetica e Cosmetica</option>
        <option>Farmacia</option>
        <option>Fisioterapia</option>
        <option>Letras</option>
        <option>Matematica</option>
        <option>Nutricao</option>
        <option>Pedagogia</option>
        <option>Psicologia</option>
        <option>Radiologia Medica</option>
        <option>Serviço Social</option>
        <option>Fotografia e Design Grafico</option>
        <option disabled>::|Cursos Superiores Tecnológicos|::</option>
        <option>Analise e Desenvolvimento de Sistemas</option>
        <option>Automacao Industrial</option>
        <option>Gestao Qualidade</option>
        <option>Gestao Financeiro</option>
        <option>Logistica</option>
        <option>Processos</option>
        <option>Gestao Recursos Humanos</option>
        <option>Teste</option>
        <option>Teste2</option>
    </select></br>

    <h4>Períodos</h4>
    <select name="periodo" id="periodo">
        <option hidden selected>Selecione o periodo</option>
        <option>Manha</option>
        <option>Noturno</option>
    </select></br>

    <h4>Semestres</h4>
    <select name="semestre" id="semestre">
        <option hidden selected>Selecione o semestre</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
        <option>7</option>
        <option>8</option>
        <option>9</option>
        <option>10</option>
    </select></br>

    <h4>Blocos</h4>
    <select name="bloco" id="bloco">
        <option hidden selected>Selecione o Bloco</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
        <option>D</option>
        <option>E</option>
        <option>F</option>
        <option>G</option>
        <option>H</option>
    </select></br>

    <h4>Pavimento</h4>
    <select name="pavimento" id="pavimento">
        <option hidden selected>Selecione o pavimento</option>
        <option>Subsolo</option>
        <option>Terreo</option>
        <option>Primeiro</option>
        <option>Segundo</option>
    </select></br>

    <h4>Salas</h4>
    <input type="text" name="sala" id="sala" placeholder="Digite o Cod. da sala"/></br>

    <input class="button" type="submit" value="Cadastrar Curso"/>

    <a href="index.php"><strong>Voltar</strong></a> 

Code addinfo.php:

<?php
 require_once 'connect.php';

// pega os dados do formuário
$curso = isset($_POST['curso']) ? $_POST['curso'] : null;
$bloco = isset($_POST['bloco']) ? $_POST['bloco'] : null;
$pavimento = isset($_POST['pavimento']) ? $_POST['pavimento'] : null;
$sala = isset($_POST['sala']) ? $_POST['sala'] : null;
$periodo = isset($_POST['periodo']) ? $_POST['periodo'] : null;
$semestre = isset($_POST['semestre']) ? $_POST['semestre'] : null;


// validação (bem simples, só pra evitar dados vazios)
if (empty($curso) || empty($bloco) || empty($pavimento) || empty($sala) || 
empty($periodo) || empty($semestre))
{
   echo "Volte e preencha todos os campos";
   exit;
}

// insere no banco
$PDO = db_connect();
$sql = "INSERT INTO curso(id_curso, curso) VALUES(:curso)";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':curso', $curso);

// insere no banco
$PDO = db_connect();
$sql = "INSERT INTO infsala(id_infsala, id_curso, periodo, semestre, bloco, 
pavimento, sala) VALUES(:periodo, :semestre, :bloco, :pavimento, :sala:)";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':periodo', $periodo);
$stmt->bindParam(':semestre', $semestre);
$stmt->bindParam(':bloco', $bloco);
$stmt->bindParam(':pavimento', $pavimento);
$stmt->bindParam(':sala', $sala);

if ($stmt->execute())
{
   header('Location: consulta.php');
}
else
{
   echo "Erro ao cadastrar";
   print_r($stmt->errorInfo());
}
?>
    
asked by anonymous 11.03.2018 / 17:48

1 answer

0

First, in HTML you should add the attribute value to selects , this will be the value passed to PHP, for example:

<h4>Períodos</h4>
<select name="periodo" id="periodo">
    <option hidden selected>Selecione o periodo</option>
    <option value="manha">Manha</option>
    <option value="tarde">Noturno</option>
</select>

Second, the course register must be separated from the infsala registry, in the way you are doing, every time there is a register in infsala there will be one in curso , even if the chosen course has already been registered, exemplifying ...

A student is registering and choosing the right course, shortly after another person chooses the same course to enroll, the result will be: two registered courses of law and in the table infsala two entries with column id_curso different even the course being the same

Then pass the course registration part, to another separate place and that only serves this, you will have to look for this data of the bank to show in select of register of infsala , something like this:

$PDO = db_connect();
$sql = "SELECT * FROM curso";
$stmt = $PDO->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

echo "
    <select name="curso" id="curso">
        <option hidden selected>Selecione o Curso</option>
";

foreach($result as $r) {
    echo "<option value='".$r["id_curso"]."'>".$r["curso"]."<option>"
}

echo "</select>";
    
11.03.2018 / 18:23