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

tez616oj  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(351)

我有一个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”并开始迭代第六个值,它可以工作,但下一个值不行。
知道我做错了什么吗?谢谢!
赫克托

brccelvz

brccelvz1#

好吧,我发现问题了。在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

谢谢你们给我的答案!
赫克托

相关问题