【问题标题】:loop for to insert row in a mysql database with php循环使用php在mysql数据库中插入行
【发布时间】:2018-11-27 19:49:00
【问题描述】:

我有一个带有 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”并开始在第六个值,它有效,但下一个值无效。

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

赫克托

【问题讨论】:

  • 把 $i 放到你的循环中 for ($i=0; $i
  • 哦,对不起,这只是一个转录问题,在代码中是正确的
  • 尝试使用mysqli_query($con, "INSERT INTO table (name) VALUES ('$name[$i]')"); .
  • 你从不检查 mysql 错误
  • 您应该使用 INSERT ON DUPLICATE、REPLACE 和 CREATE IF NOT EXIST(不需要 if else)和安全使用绑定 w3schools.com/php/php_mysql_prepared_statements.asp

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


【解决方案1】:

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

感谢大家的启发!

赫克托

【讨论】:

    猜你喜欢
    • 2012-04-23
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多