Pass the value of the primary key of a table to the foreign one of another PHP table

0

I have already used MAX (column_name), last_insertid, and nothing works, the foreign key of the second table continues to get value 0.

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

    $conexao = Database::getConnection();

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

    $conexao->exec($sql);
}

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

 $ficha = new Cabecalho();
 $nr_ficha = $ficha->busca_ficha();
 $cod_refugo_teste = $_POST['cod_refugo_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($nr_ficha, $cod_refugo_teste, $qtd_refugo, $codigo);
header("location:../?pgs=modal_cadastro_teste");
    }else{
        echo "Erro!";
    }

.

public function busca_ficha(){
$conexao = Database::getConnection();

$select="SELECT MAX(nr_ficha) FROM cab_teste";

  $busca = $conexao->query($select);
  $nr_ficha = $busca->fetchAll(PDO::FETCH_ASSOC);

  return $nr_ficha;
 }

nr_file is the primary key of table 1.

Test_text_nistheforeignkeyoftable2.

AN ADDENDUM: value was getting zero because it was not really a foreign key, BUT I still can not pass any value to nr_ficha_teste. Now that I've connected the two tables, the FK of table 2 gets NULL.

    
asked by anonymous 22.08.2018 / 15:08

1 answer

0

Well, I got it sorted out. The problem was not in the bank, but in php. At the time of passing the value, I made the variable into an array. To make the array work, just IN MY CASE, give a nickname to the column and pass that nickname as a parameter. It looks like this:

public function busca_ficha(){
 $conexao = Database::getConnection();

 $select="SELECT MAX(nr_ficha) AS ULTIMO FROM cab_teste";

 $busca = $conexao->query($select);
 $nr_ficha = $busca->fetchAll(PDO::FETCH_ASSOC);

 return $nr_ficha[0]['ULTIMO'];
}
    
29.08.2018 / 13:24