谁能让我知道为什么此PDO语句在for循环中不起作用?我正在尝试向数据库中每个新条目的位置添加一个。由于某种原因,这种情况正在中断。有什么想法吗?

编辑

请忽略下一个位置,等等。由于其他原因,gp_position不能为AUTO_INCREMENT,并且下一个位置将不会始终从1开始。

    $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++;
    }

最佳答案

试试下面的重构代码:

$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++;
}

关于php - PDO INSERT语句在计数器循环内不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25856327/

10-11 15:22