【发布时间】: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