Problems fetching the id of the previous insert

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 $last_id variable. When I enter two new managers, the first insert will insert two lines with two ids different, for example:

  • id = 10 IdResponsável = Alberto IdUtente = 10115
  • id = 11 IdResponsible = Armindo IdUtente = 10118

Then, when doing the second insert , the id that it takes from the previous table is always in the last one for both registers and can not, has to get the first insert id = 10 and second the id = 11 .

    
asked by anonymous 20.12.2018 / 18:53

1 answer

1

The problem that the $last_id variable is outside of the loop repetition, there are 2 ways to solve, you can put the second INSERT inside the first loop repeat or you can create a% I want to insert the second INSERT (which 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);
}
    
20.12.2018 / 21:02