phphtmlmysqlcheckboxmaterial-design-lite

PHP change multiple values of database through checkboxes boolean


I am trying to make some sort of simple blogging platform and it has been going pretty well until now, my page has a list of articles on it in a table it gets that list from my SQL database and there is also a column which states if the article is public or isn't. The problem is I can't get the writing of all these checkboxes as a boolean to work (if checked input 1 else 0). The part I think it goes wrong is:

<?php
if (isset($_POST['submit'])) {
    try {
        $stmt = $db->prepare('SELECT postID FROM blog_posts') ;
        $idArray = $stmt->fetch();

        for($i = $idArray; $i > 0; $i--){
            if(document.getElementById($i).checked){
                $public = 1;
            } else {
                $public = 0;
            }

            try {
                $stmt = $db->prepare('UPDATE blog_posts SET public = :public WHERE postID = '$i) ;
                $stmt->execute(array(
                    ':public' => $public
                    ));
            }
        }
    }
?>

The entire code can be found here on Hastebin


Solution

  • Name your public checkboxes using an array format, so that each one has the id in its name like this:

    <input type="checkbox" name="public[<?php echo $postID ?>]">
    

    Then you can use this PHP code to do your updates:

    if (isset($_POST['submit'])) {
    
        // You can use query here instead of prepare if you want all the blog posts
        $stmt = $db->query('SELECT postID FROM blog_posts');
    
        // fetch the postID from each row in the query result
        while ($id = $stmt->fetchColumn()) {
    
            // set public based on the submitted value from your form
            $public = empty($_POST['public'][$id]) ? 0 : 1;
    
            // do the update
            $stmt = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?') ;
            $stmt->execute(array($public, $id);
        }
    }
    

    Note that you are SELECTing every blog post, so if your form does not include every blog post, this code will set every one that isn't on your form to public=0. If you aren't displaying every blog post on your form, you'll need to add a WHERE clause to your SELECT statement so that it only includes the rows that are included in your form.