循环使用php在mysql数据库中插入行

时间:2018-11-27 19:49:00

标签: php mysql for-loop if-statement sql-insert

我在php中有一个for循环,但不能正常工作。在for循环中,我有一个“ if”和一个“ else”,但是循环在第一个“ else”中停止迭代,应该继续。这是代码:

//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);

  // here is the next code

  $newTable = 'table'.$rowToInsert[$i];

  $newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
  $resultDB = mysqli_query($con, $newDB);

  // select the DB

  mysqli_select_db($con, $newTable) or die ("not found");

  } //end of else

} //end of for

问题是,如果数据库包含5行,而我想插入10行,则代码将使用新值更新前5行,然后跳转到“ else”并开始在第六个值,它起作用,但下一个值不起作用。

知道我在做什么错吗?谢谢!

赫克托

1 个答案:

答案 0 :(得分:0)

好,我发现了问题。在else循环中,当迭代尝试选择数据库时,由于某种原因,它使用了上一次迭代的名称,因此找不到数据库。解决方案(也许不是那么干净)是在每次迭代中连接并关闭数据库连接。代码如下:

//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

   // reconnect to db

   $con = mysqli_connect($host, $user, $pass) or die ("unable to connect");
   $db = "database";

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

  // here is the next code

  $newTable = 'table'.$rowToInsert[$i];

  $newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
  $resultDB = mysqli_query($con, $newDB);

  // select the DB

  mysqli_select_db($con, $newTable) or die ("not found");

  //close the connection to db;

  $con->close();

  } //end of else

} //end of for

感谢大家启发答案!

赫克托