How to enter the generated id in the Insert as a foreign key from another table?

Asked

Viewed 345 times

-1

<?php
      include_once "./Models/Usuario.php";
      include_once './Models/Login.php';
      include_once './Models/Profissional.php';
      include_once './Models/Cabecalho.php'; 
      include_once './Models/Teste.php'; 

?>

<!DOCTYPE html>
<html>
	<head>
	 	<meta charset="UTF-8">
      <link href="./semantic/js/dropdown.css" rel="stylesheet">
	    <link href="./semantic/semantic.css" rel="stylesheet">
	    
	    <title> cabecalho de cabecalho </title>
	</head>
<body>



<?php

@$usuario = new Login();
@$cod_usuario = $usuario->retorna_codigo_usuario();

@$user = new Login();
@$in_user=$user->taLogado();
@$tipo_user = $user->retorna_tipo();
	if ($in_user == false){ 
    header('location:?pgs=inicial');
} 



		if ($tipo_user == 2 ) {
?>
<div class="ui stackable centered grid">
  <div class="ui eight wide column">
  <h2 class="ui horizontal divider header">
    <div class="content">
      Cadastrar novo cabeçalho
    </div>
    </h2>
			<form class="ui form" method="POST" name="nr_ficha" action="./Controllers/processa_cab_teste.php" enctype="multipart/form-data">
    		<div class="ui stacked secondary segment">
            <div class="three fields">
              <div class="field">
                <label>Código do produto</label>
                <input type="text" name="cod_produto_cabecalho" placeholder="Exemplo: D21" required value="<?= @$_SESSION['dados_cabecalho']['cod_produto_cabecalho']; ?>">
              </div>
              <div class="five wide field">
                <label>Data</label>
                <input type="date" name="data_cabecalho" placeholder="Exemplo: " required value="<?= @$_SESSION['dados_cabecalho']['data_cabecalho']; ?>">
              </div>
              <div class="field">
                <label>Hora</label>
                <input type="time" name="hora_cabecalho" required value="<?= @$_SESSION['dados_cabecalho']['hora_cabecalho']; ?>">
              </div>
            </div>
            <div class="two fields">
              <div class="field">
                <label>Responsável</label>
                <input type="text" name="responsavel_cabecalho" placeholder="Exemplo: Ana" required value="<?= @$_SESSION['dados_cabecalho']['responsavel_cabecalho']; ?>">
              </div>
              <div class="field">
                <label>Total testado</label>
                <input type="text" name="qtd_cabecalho" placeholder="Exemplo: 340" required value="<?= @$_SESSION['dados_cabecalho']['qtd_cabecalho']; ?>">
              </div>
            </div>
              <p></p>
          <input type="hidden" name="cod_cabecalho_profissional" value='<?=$cod_usuario; ?>' method="POST">
            <button type="submit" name="nr_ficha" class="ui fluid large grey submit button" value="<?php echo $id; ?>">Continuar
            </button>
    			</form>
      </div>
        </div>
		<?php }
  else{
			echo "";
		}

  



?>
   
  </div>
</div>




</body>
</html>
































<?php
      include_once "./Models/Usuario.php";
      include_once './Models/Login.php';
      include_once './Models/Profissional.php';
      include_once './Models/Teste.php'; 
      include_once './Models/Cabecalho.php';
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
      <link href="./semantic/js/dropdown.js" rel="stylesheet">
      <link href="./semantic/semantic.css" rel="stylesheet">

      <title> Cadastro de teste </title>
  </head>
<body>



<?php


@$usuario = new Login();
@$cod_usuario = $usuario->retorna_codigo_usuario();

@$user = new Login();
@$in_user=$user->taLogado();
@$tipo_user = $user->retorna_tipo();
  if ($in_user == false){ 
    header('location:?pgs=inicial');
} 


$cabecalho = new Cabecalho();
$nr_ficha = $cabecalho->busca_cabecalho();

          

    if ($tipo_user == 2 ) {?>
<div class="ui stackable centered grid">
  <div class="ui eight wide column">
  <h2 class="ui horizontal divider header">
    <div class="content">
      Cadastrar novo teste
    </div>
    </h2>
      <form class="ui form" method="POST" action="./Controllers/processa_testeq.php" enctype="multipart/form-data">
        <div class="ui stacked secondary segment">
          <div class="two fields">
            <div class="field">
              <label>Refugo</label>
              <input type="text" name="cod_refugo_teste" required>
            </div>
            <div class="field">
              <label>Quantidade</label>
              <input type="text" name="qtd_refugo" required>
            </div>
          </div>
        </form>
            <p></p>
            <input type="hidden" name="nr_ficha_teste"  value='<?='$nr_ficha'; ?>'>
          <input type="hidden" name="cod_usuario_profissional" value='<?=$cod_usuario; ?>' method="POST">
            <button type="submit" name="" class="ui fluid large grey submit button">Continuar</button>
          </form>
      </div>
        </div>
    <?php }else{
      echo "";
    }
?>
   
  </div>
</div>
</body>
</html>

<?php

require "../Models/Cabecalho.php";
require "../Models/Profissional.php";


$data_cabecalho = date($_POST['data_cabecalho']);
$responsavel_cabecalho = $_POST['responsavel_cabecalho'];
$qtd_cabecalho = $_POST['qtd_cabecalho'];
$hora_cabecalho = $_POST['hora_cabecalho'];
$cod_produto_cabecalho  = $_POST['cod_produto_cabecalho'];
$codigo = $_POST['cod_cabecalho_profissional'];
$nr_ficha = $_GET['nr_ficha'];
					
	$cabecalho = new Cabecalho();
	$cabecalho->cadastrar_cabecalho($data_cabecalho, $responsavel_cabecalho, $qtd_cabecalho, $hora_cabecalho, $cod_produto_cabecalho, $codigo);
	header("location:../?pgs=form_testeq");
		
    
    
    
    
    
    
    
<?php

require "../Models/Teste.php";
require "../Models/Profissional.php";


$cod_refugo_teste = $_POST['cod_refugo_teste'];
$nr_ficha_teste = $_POST['nr_ficha_teste'];
$qtd_refugo = $_POST['qtd_refugo'];
$codigo = $_POST['cod_usuario_profissional'];
$valoresrefugos = explode(",",$cod_refugo_teste);
$valoresqtds = explode(",",$qtd_refugo);


$unir = 'INSERT INTO teste (cod_refugo_teste, qtd_refugo) VALUES (';
for ($i = 0; $i < count($valoresrefugos); $i++) {
	if ($i == count($valoresrefugos) - 1) {
		$unir .= "'" . $valoresrefugos[$i] . "','" . $valoresqtds[$i] . "')";
	}
	else {
		$unir .= "'" . $valoresrefugos[$i] . "','" . $valoresqtds[$i] . "'), (";
	}
}


			
if (is_numeric($codigo)){			
	$teste = new Teste();
	$teste->cadastrar_teste($cod_refugo_teste, $qtd_refugo, $nr_ficha_teste, $codigo);
	header("location:../?pgs=modal_cadastro_teste");
		}else{
			echo "Erro!";
		}
    

I want to add the primary key of a table to a foreign key of another table. The primary key of Tabela1 is auto increment, and when passing to the second table, the value appears null. How do I through the database this action?

Note: The primary key of the first table (cab_test) is nr_ficha, which is not there because it is autoincrement. And the foreign key of the test table is nr_ficha_test.

public function cadastrar_cabecalho($data_cabecalho, $responsavel_cabecalho, $qtd_cabecalho, $hora_cabecalho, $cod_produto_cabecalho, $codigo_profissional){
    $conexao = Database::getConnection();

    $sql = "INSERT INTO cab_teste (data_cabecalho, responsavel_cabecalho, qtd_cabecalho, hora_cabecalho, cod_produto_cabecalho, cod_cabecalho_profissional)
            VALUES ('$data_cabecalho', '$responsavel_cabecalho', '$qtd_cabecalho', '$hora_cabecalho', '$cod_produto_cabecalho', '$codigo_profissional');";

    $conexao->exec($sql);
}

public function cadastrar_teste($cod_refugo_teste, $qtd_refugo, $nr_ficha_teste, $codigo_profissional){

    $conexao = Database::getConnection();

    $sql = "INSERT INTO teste (cod_refugo_teste, qtd_refugo, nr_ficha_teste, cod_usuario_profissional)
            VALUES ('$cod_refugo_teste', '$qtd_refugo', '$nr_ficha_teste', '$codigo_profissional');";

    $conexao->exec($sql);
}
  • 1

    What is the primary key? What is the foreign key? How did you pass the value? How did you get the id that was generated in Insert? And finally, nothing here is urgent - unless someone is dying, then we make an exception :D

  • I put as observation the first two questions. The rest I do not know answer because it is precisely at the time of pulling the value that I lose myself.

  • 1

    Place the code where you call the methods cadastrar_cabecalho and cadastrar_teste.

1 answer

2

In the PHP there is a specific function to take the last inserted ID.

Mysqli

If used MySQLi can use procedural mode or OO mode.

Procedural mode

mysqli_insert_id($conexao);

Oo mode

$conexao->insert_id;

PDO

If used PDO may use as follows:

$conexao->lastInsertId();

Solution for you

In your case, you can change the function cadastrar_cabecalho to return the ID registered (as shown below). With this just catch the ID returned and pass in function cadastrar_teste.

public function cadastrar_cabecalho($data_cabecalho, $responsavel_cabecalho, $qtd_cabecalho, $hora_cabecalho, $cod_produto_cabecalho, $codigo_profissional){
    $conexao = Database::getConnection();

    $sql = "INSERT INTO cab_teste (data_cabecalho, responsavel_cabecalho, qtd_cabecalho, hora_cabecalho, cod_produto_cabecalho, cod_cabecalho_profissional)
            VALUES ('$data_cabecalho', '$responsavel_cabecalho', '$qtd_cabecalho', '$hora_cabecalho', '$cod_produto_cabecalho', '$codigo_profissional');";

    $conexao->exec($sql);
    return mysqli_insert_id($conexao);
}
  • Anyway, once the test registration form processes the data, this error appears: Notice: Undefined variable: nr_ficha_test in C: xampp htdocs TESTE_BANCADA Controllers processes_testeq.php on line 29

  • And soon after a fatal error appears saying that I can’t add or delete any value within nr_ficha_test

  • how is making the call of methods now?

Browser other questions tagged

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