Problems picking up the previous Insert id

Asked

Viewed 39 times

0

Code to insert:

$codigoutente = $_POST['codigoutente']; 
$codvalencia = $_POST['codvalencia']; 
$Responsavel = $_POST['Responsavel'];
$Contato = $_POST['Contato']; 

for ($i=0;$i<count($_POST["Responsavel"]);$i++) { 
$Responsavel = $_POST['Responsavel'][$i];

$stmt1 = $conn->prepare("INSERT INTO Responsaveis (`Responsavel`,`IdUtente`) VALUES ('$Responsavel','$codigoutente')");
mysqli_stmt_execute($stmt1);
}
$last_id = $conn->insert_id;


for ($i=0;$i<count($_POST["Contato"]);$i++) { 
$Contato = $_POST['Contato'][$i];

$stmt2 = $conn->prepare("INSERT INTO ContatoRes (`IdUtente`,`IdResponsavel`,`Contato`) VALUES ('$codigoutente','$last_id','351$Contato')");
mysqli_stmt_execute($stmt2);
}

The problem is the variable $last_id. When I insert two new guardians into the first insert will insert two lines with two ids different, example:

  • id = 10 Idresponsable = Alberto Idutente = 10115
  • id = 11 Idrsponsable = Arming Idutente = 10118

Then when doing the second insert the id taken from the previous table is always in the latter for the two records and cannot, you have to take the first insert the id = 10 and in the second the id = 11.

  • $_POST["Contato"] and $_POST["Responsavel"]are arrays that are receiving ?

1 answer

1


The problem that the variable $last_id this out of the repeat loop, there are 2 ways to solve, you can put the second INSERT within the first loop of repetition or can create a vector of $last_id to scroll again when the second is inserted INSERT (which is what I did in the code below).

$codigoutente = $_POST['codigoutente']; 
$codvalencia = $_POST['codvalencia']; 
$Responsavel = $_POST['Responsavel'];
$Contato = $_POST['Contato']; 

for ($i=0;$i<count($_POST["Responsavel"]);$i++) { 
$Responsavel = $_POST['Responsavel'][$i];

$stmt1 = $conn->prepare("INSERT INTO Responsaveis (`Responsavel`,`IdUtente`) VALUES ('$Responsavel','$codigoutente')");
mysqli_stmt_execute($stmt1);
$last_id_array[] = $conn->insert_id;
}


for ($i=0;$i<count($_POST["Contato"]);$i++) { 
$Contato = $_POST['Contato'][$i];
$last_id = $last_id_array[$i];
$stmt2 = $conn->prepare("INSERT INTO ContatoRes (`IdUtente`,`IdResponsavel`,`Contato`) VALUES ('$codigoutente','$last_id','351$Contato')");
mysqli_stmt_execute($stmt2);
}

Browser other questions tagged

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