Get the last ID of a table 1 and then insert it into a table 2 using PHP

1

I have two related tables and I want to get the last ID_primeraTabla to insert it in the second table since the ID_primeraTabla is the foreign key. any ideas ?

What I have is the following

$pregunta = $_POST["pregunta"]; 
    $respuesta = $_POST["respuesta"];
    $comentario = $_POST["comentario"];

    $sql = "Select id_asistente FROM Asistente order by id_asistente DESC LIMIT 1";
    mysqli_query($connect, $sql) or die (mysqli_error($connect));

$query = "Insert into Encuesta_asistente(pregunta_encuesta,respuesta_encuesta,comentario_encuesta,id_asistente) values ('$pregunta','$respuesta','$comentario','$sql');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
    
asked by Ashley G. 01.02.2017 в 20:16
source

1 answer

1

The problem is that you are not receiving the value of the first query anywhere.

I put the complete code with comments:

$pregunta   = $_POST["pregunta"];
$respuesta  = $_POST["respuesta"];
$comentario = $_POST["comentario"];

$sql = "Select id_asistente FROM Asistente order by id_asistente DESC LIMIT 1";

// Pasamos el resultado
$resultado = mysqli_query($connect, $sql) or die (mysqli_error($connect));

// Pasamos a un array asociativo 
$id_resultado = mysqli_fetch_array($resultado, MYSQLI_ASSOC);

$id_asistente = $id_resultado['id_asistente'];

// La $id_asistente será un numero entero así que he elminado las comillas simple
$query = "

    Insert 
    into Encuesta_asistente(pregunta_encuesta,respuesta_encuesta,comentario_encuesta,id_asistente) 
    values ('$pregunta','$respuesta','$comentario', $id_asistente ); ";


mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);

Important Note : Please use prepared statements MySQLi or better PDO to avoid possible attacks from SQL Injections

    
answered by 01.02.2017 / 20:43
source