开发者

How do I get this php statement that gets all the values from database and outputs as checkboxes to work? (PHP/Mysql)

I am a bit lost in all these "" and '' and . in this statement. Basically this query is to get all the tagname from table "tag" and display them for the users as checkboxes. If they have clicked 'submit' and they missed another field(sa开发者_StackOverflow中文版y the title of a post), it would still have the tag they chose displayed. The part I need help with is the echoing part. It doesn't seem to remember the tag when they click submit.

      $query4 = "SELECT * FROM tags  ORDER BY tagname";
  $data4 = mysqli_query($dbc, $query4);
  while ($row4 = mysqli_fetch_array($data4)) 
  {
  echo "<li><input type='checkbox' name='postingtag[]'";
  if (!empty($postingtag)){
   echo "value='$postingtag'";
  }
  else{
   echo "value='{$row4['tagID']}'";
  }
  echo ">{$row4['tagname']}</li>";
  }


Try this:

$query4 = "SELECT * FROM tags  ORDER BY tagname";
$data4 = mysqli_query($dbc, $query4);
while ($row4 = mysqli_fetch_array($data4)) {

 echo "<li><input type='checkbox' name='postingtag[{$row4['tagID']}]' value='1'";

 if (isset($postingtag[$row4['tagID']]))
  echo " checked='checked'";

 echo "/> {$row4['tagname']}</li>";
}

$postingtag will be an array that will be populated with tags that have been checked. By adding a discernible index to the $postingtag array you'll be able to check to see if its be populated and can then set the checked attribute accordingly.


In order to determine whether a user checked a certain checkbox on a form submit, you need the test whether the checkbox was submitted. You see, browsers only send the value of the checkbox if it is checked, otherwise you receive nothing. So, in order to test for this, you need a way to uniquely identify this checkbox in the submitted parameters. The most reliable way to do this in this case (and most other, if not all other cases), is to include the unique tag id as the key of the name of the checkbox, like so:

... <li><input type="checkbox" name="postingtag[' . $row4[ 'tagID' ] . ']" ...

Then on submission test for it with:

$checked = isset( $_POST[ 'postingtag' ][ $row4[ 'tagID' ] ] ) ? ' checked="checked"' : '';

Putting it all together you'ld get something like:

$checked = isset( $_POST[ 'postingtag' ][ $row4[ 'tagID' ] ] ) ? ' checked="checked"' : '';
$checkbox = '<li><input type="checkbox" name="postingtag[' . $row4[ 'tagID' ] . ']"' . $checked . '>' . $row4['tagname'] . '</li>';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜