It happened to me the same way and I corrected it like that.
Context: I create a support ticket. The Ticket and its properties are in a table, and the messages of the tickets are saved in another. So when creating a ticket, I have to create it in the tickets table and insert its corresponding message in another table. Then, I create the ticket and retrieve its ID at that moment and return it to a function where it immediately inserts the message with the recovered ID.
I had something like that.
Function that creates the ticket:
public function crearTicketController($idUsuario, $asunto, $prioridad, $mensaje, $clase){
$idu= $idUsuario;
$as= $asunto;
$p = $prioridad;
$c =$clase;
#primero se inserta el ticket y se obtiene el último ID de la tabla ticket
$idticket = Datos::crearTicketModel($idUsuario, $asunto, $prioridad, $mensaje, $clase);
#ahora inserto el mensaje
$respuesta = Datos::mensajeTicketModel($idticket, $idu, $text, $c);
if($respuesta==1){
echo '
<script type="text/javascript">
window.setTimeout(function(){
window.location="panel.php?modulo=tickets&action=ver&id='.$idticket.'";
}, 0);
</script>
';
}
else{
echo "error";
}
}
Function that inserts the ticket:
public function crearTicketModel($idUsuario, $asunto, $prioridad, $mensaje, $clase){
$stmt = Conexion::conectar()->prepare("INSERT INTO tickets (idusuario, asunto, prioridad, fecha, estado) VALUES (:idusuario, :asunto, :prioridad, now(), 1 )");
$stmt->bindParam(":idusuario", $idUsuario, PDO::PARAM_INT);
$stmt->bindParam(":asunto", $asunto, PDO::PARAM_STR);
$stmt->bindParam(":prioridad", $prioridad, PDO::PARAM_INT);
if($stmt->execute()){
$stmt= Conexion::conectar()->prepare("SELECT MAX(id) as idTicket FROM tickets");
if($stmt->execute()){
$idticket = $stmt->fetch(PDO::FETCH_ASSOC);
$myidticket = $idticket["idTicket"];
return $myidticket;
}else{
$respuesta = $this->mensajeError();
}
}else{
$respuesta = $this->mensajeError();
}
}
Function that inserts the ticket message:
public function mensajeTicketModel($idTicket, $idUsuario, $mensaje, $clase){
$id = $idTicket;
$stmt = Conexion::conectar()->prepare("INSERT INTO detalletickets (idticket, idusuario, texto, fecha, clase) VALUES (:idticket, :idusuario, :mensaje, now(), :clase )");
$stmt->bindParam(":idticket", $idTicket, PDO::PARAM_INT);
$stmt->bindParam(":idusuario", $idUsuario, PDO::PARAM_INT);
$stmt->bindParam(":mensaje", $mensaje, PDO::PARAM_STR);
$stmt->bindParam(":clase", $clase, PDO::PARAM_INT);
if($stmt->execute()){
return 1;
}
else{
return 0;
}
}
I hope it serves you, that way I solved it and there is no failure. Greetings.