我目前正在为我的mySQL数据库编写一个php加载器。 用户输入用户密码并写入要插入的数据库表,然后从
中选择一个区域表单操作转到database.php以使用POST
进行插入我在database.php中的代码是:
$region = $_POST["region"];
$tablename = $_POST["tableName"];
$accounts = explode(PHP_EOL, $_POST["accountlist"]);
$quantity = sizeof($accounts);
// Batch size, calc iterations
$batchSize = 500;
for($idx=0;$idx*$batchSize < $quantity; $idx++){
$accountsPartial = array_slice($accounts, $idx*$batchSize, $batchSize);
// Prepare the Query
$query = "INSERT INTO $tablename (username, password, region) VALUES (?, ?, ?)";
// Create the multiple value placeholder
$db = $db->prepare($query);
foreach($accountsPartial as $item){
$i = 1;
list($user, $pass) = explode("|", $item);
$db->bindValue($i++, trim($user));
$db->bindValue($i++, trim($pass));
$db->bindValue($i++, trim(strtoupper($region)));
$db->execute();
}
}
我的问题是,当我发送超过500个值时,只有500个帐户获得了Insereted。 我很乐意得到一些帮助和建议如何解决这个问题 提前谢谢!
答案 0 :(得分:1)
你的循环代码基本没用。由于您要插入POST中的所有数据,因此您应该这样做:
$query = "INSERT INTO $tablename (username, password, region) VALUES (?, ?, ?)";
// Create the multiple value placeholder
$stmt = $db->prepare($query);
$stmt->bindValue(1, $user);
$stmt->bindValue(2, $pass);
$stmt->bindValue(3, $region)
$region = trim(strtoupper($region));
foreach($accountsPartial as $item){
list($user, $pass) = explode("|", $item);
$user = trim($user);
$pass = trim($pass);
$stmt->execute();
}
注意变量 OUTSIDE 与循环的绑定,以及与实际变量的绑定,而不是trim()调用的结果。
同样,正如所写,您的代码正在删除您的数据库连接,使用相同的变量将您准备好的语句保存为数据库连接本身:
$db = $db->prepare(...);
会破坏你的数据库连接,使其余代码无法实现。
答案 1 :(得分:0)
如果要插入600而不是500 do {} while ()
和$idx = 2
并且正在退出循环,则应使用$idx * $batchSize = 1000 < 600
循环原因。