lundi 24 août 2015

Getting an alternate value for an unchecked checkbox?

I've seen a solution here that I, quite frankly, don't understand.

On the administration side of a website I'm working on, an administrator can edit blog posts. When the administrator goes to the page to edit the blog post, it also displays all of the comments on that post. Instead of adding a new table for each new blog post which contains comments, I simply created one table which holds all the information for the blog post, including a column for the comments.

Comments and comment-content is delimited. I.E. internally, a blog post comment column would look similar to this...

Name:Content:Email>Name2:Content2:Email

Etc.

This is how I display the comments on the admin page:

$post_query = "SELECT * FROM `$blog_table` WHERE id=$identifier";
$post_result = $connection->query($post_query);
$post = $post_result->fetch_assoc();
$comments_value = $post["comments"];
$original_comments_array = explode(">", $comments_value);
$comments_array = [];
foreach($original_comments_array as $comment) {
  $individual_comment_array = explode(":", $comment);
  $comments_array[] = $individual_comment_array;
}
foreach($comments_array as $index=>$comment) {
          if ($comment_deletions_array[$index] === $index) {
            $checked = "checked";
          }
          echo '<div class="content-border comment-margin"><span class="comment-name">';
            echo $comment[0];
            echo '</span><br /><p class="comment-content">';
            echo $comment[1];
            echo '<br /></p>';
            echo $comment[2];
            echo '<br /><br /><input name="comment_deletions[]" type="checkbox" value="' . $index . '" ' . $checked . '/> Delete This Comment';
          echo '</div>';
        }

As you may have noticed from the code above, each comment renders with its own checkbox input, the value of which is determined by the index.

Each checkbox shares the same name. I get all the values of the checkboxes like this:

$comment_deletions_array = $_POST["comment_deletions"];

In the snippet I provided earlier, there is an if statement within the foreach loop which determines if the comment was marked for deletion, and if so checks the check box. (This function is to replace the user's input if there was an error.)

The problem is that the indexes do not line up. If there is a checkbox which is not checked, it does not return false or null or anything of the sort to the $comment_deletions_array rather the array is just populated by value of the next input which WAS checked.

Is there a way I can return a value if the checkbox is not checked in order to maintain the correct index?




Aucun commentaire:

Enregistrer un commentaire