PHP虽然ID的循环仅适用于第一个id

时间:2016-07-03 09:19:56

标签: php mysql material-design-lite

我目前正在使用一些不错的Material Design构建一个轻量级的博客平台,但我遇到了一个问题。我有一个带ID的表,我想在我的表中更改public的值,以便你可以隐藏博客中的文章,这样做我做了一个循环,但它只适用于第一个id而没有其他的身份证。这是我的代码:

        try {
        if (isset($_POST['submit'])) {
            $stmt = $db->query('SELECT postID FROM blog_posts ORDER BY postID DESC');

            while ($row = $stmt->fetch()) {
                // set public based on the submitted value from your form
                $public = empty($_POST['public'][$row['postID']]) ? 0 : 1;

                // do the update
                $stmt = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?');
                $stmt->execute(array($public, $row['postID']));
                header('Location: index.php');
            }
        }
    } catch (PDOException $e) {
        echo $e->getMessage();
    }

如果有任何用途here是我的PHP整页,也可以找到我的完整页面here

提前致谢。

1 个答案:

答案 0 :(得分:0)

请将此header('Location: index.php');放在while循环之外,不要覆盖$stmt而是使用另一个:

//.......
//.......
while ($row = $stmt->fetch()) {

    // set public based on the submitted value from your form    
    $public = empty($_POST['public'][$row['postID']]) ? 0 : 1;

    // do the update  
    //Create another statement
    $stmt2 = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?');
    $stmt2->execute(array(
        $public,
        $row['postID']
    ));
}

header('Location: index.php');
//.......
//.......