PDO语句在循环内循环

时间:2014-01-14 08:54:23

标签: php arrays pdo foreach sql-insert

使用prepare语句向我的数据库插入一个语句数组。但我正面临着正确插入问题的问题。我的代码看起来像这样 我有$ requests数组

(
    [0] => 456908497765326_100004069844270
    [1] => 456908497765326_100000058716604
)

$stmt = $this->core->dbh->prepare("INSERT INTO fb_requests(user_id,fb_user_id,request_id,game_selected,accept_status) VALUES(:user_id,:fb_user_id,:request_id,:game_selected,:outstanding)");
for($i=0;$i<2;$i++){
    echo "counter value".$i; echo"</br>";
    foreach($requests as $requestid) {
        echo "request value".$requestid; echo"</br>";
        $stmt->execute(array('user_id'=>$user_id,':fb_user_id' => $uid, ':request_id' => $requestid,':game_selected' => $i, ':outstanding' => $outstanding));
    }
}

插入仅适用于内部foreach循环。我可以看到两行插入到我的数据库中。但外部for循环不起作用。我希望在我的数据库中插入4行。请帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

你可能在某个地方有一个独特的索引。

$stmt = $this->core->dbh->prepare("
    INSERT INTO fb_requests (user_id, fb_user_id, request_id, game_selected, accept_status)
    VALUES (:user_id, :fb_user_id, :request_id, :game_selected, :outstanding)
");

for($i = 0; $i < 2; $i++) {
    echo "counter value $i<br>";
    foreach($requests as $requestid) {
        echo "request value $requestid<br>";
        try {
            $stmt->execute(array(
                'user_id' => $user_id,
                'fb_user_id' => $uid,
                'request_id' => $requestid,
                'game_selected' => $i,
                'outstanding' => $outstanding
            ));
        } catch (PDOException $e)
        {
            var_dump($e->getMessage());
        }

        var_dump($stmt->errorInfo());
    }
}

您应该尝试捕获任何异常以查看正在发生的事情。我编辑了你的代码以添加一些格式,以便我可以阅读它。试一试,看看问题是什么(如果有的话)goi