繁体   English   中英

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

[英]loop for to insert row in a mysql database with php

我有一个用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”并开始迭代第6个值,它起作用,但下一个值不起作用。

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

赫克托

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

谢谢大家启发答案!

赫克托

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM