我有一个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条答案
按热度按时间brccelvz1#
好吧,我发现问题了。在else循环中,当迭代尝试选择数据库时,由于某种原因,它使用上一次迭代的部分名称,因此它找不到数据库。解决方案(可能不是很干净)是在每次迭代中连接并关闭数据库连接。代码保持如下:
谢谢你们给我的答案!
赫克托