mardi 27 novembre 2018

loop for to insert row in a mysql database with php

I have a for loop with php but is not working properly. Inside the for loop I have an "if" and an "else", but the loop stops iterate in the first "else" and should continue. Here is the code:

//counting the rows in database and the rows I want to insert

$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values

// the for loop starts

for ($i=0; $i < $total; $i++){ //it should iterate until 10 values

  if(isset($rowDB[$i])){ //change the first 5 values

   $update = "UPDATE table SET name = '$name[$i]' WHERE ID = '$rowToInsert[$i]'";
   $result = mysqli_query($con, $update);

  } else { //it should iterate from sixth until tenth value

   $insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
   $result = mysqli_query($con, $insert);

  } //end of else

} //end of for

The thing is if the database contain 5 rows and I want to insert, for example, 10 rows, the code works updating the first 5 with the new value, then it jumps to the "else" and starts to iterate in the sixth value and it works, but the next values doesn't.

Any idea what i'm doing wrong? Thanks!

Hector

Aucun commentaire:

Enregistrer un commentaire