任何人都可以告诉我为什么这个PDO声明在for循环中不起作用?我试图为数据库中的每个新条目添加一个位置。由于某种原因,这是打破。关于为什么的任何想法?
修改
请忽略下一个位置等。由于其他原因gp_position
不能AUTO_INCREMENT
,下一个位置不会始终从1开始。请关注此PDO声明赢得的原因&# 39;在循环中工作。
$nextPosition = 1;
$imgID = 1;
$indb_gridID = 1;
$timesToRepeat = 33;
$indb_mem_id = ($this->user->is_logged_in()) ? $this->user->info['id'] : 1;
for($i=1; $i<=$timesToRepeat; $i++) {
// now add the image to the grid positions
$stmt = dbpdo::$conn->prepare("INSERT INTO grid_positions SET
gp_mem_id = :memID,
gp_g_id = :gridID,
gp_img_id = :imgID,
gp_position = :position");
$stmt->bindParam(':memID', $indb_mem_id, PDO::PARAM_INT);
$stmt->bindParam(':gridID', $indb_gridID, PDO::PARAM_INT);
$stmt->bindParam(':imgID', $imgID, PDO::PARAM_INT);
$stmt->bindParam(':position', $nextPosition, PDO::PARAM_INT);
$stmt->execute();
$nextPosition++;
}
答案 0 :(得分:0)
试试这个重构的代码:
$nextPosition = 1;
$imgID = 1;
$indb_gridID = 1;
$timesToRepeat = 33;
$indb_mem_id = ($this->user->is_logged_in()) ? $this->user->info['id'] : 1;
// prepare the statement once:
$stmt = dbpdo::$conn->prepare("INSERT INTO grid_positions SET
gp_mem_id = :memID,
gp_g_id = :gridID,
gp_img_id = :imgID,
gp_position = :position");
$stmt->bindParam(':memID', $indb_mem_id, PDO::PARAM_INT);
$stmt->bindParam(':gridID', $indb_gridID, PDO::PARAM_INT);
$stmt->bindParam(':imgID', $imgID, PDO::PARAM_INT);
$stmt->bindParam(':position', $nextPosition, PDO::PARAM_INT);
for($i=1; $i<=$timesToRepeat; $i++) {
// exec statement with current values:
$stmt->execute();
$nextPosition++;
}