Jump to content

Multiple checkboxes in form from database


robcrozier

Recommended Posts

Hi guys, i wonder if anyone can point me in the right direction with this.  What i want to do is generate a number of checkboxes on a form based on the number of rows retrieved from a certain MySQL table.  for example if table1 returns 5 rows, i want to generate 5 different checkboxes on the form that the user can select.  I then want to pass the value(s) back to the validation script when the form is submitted.

 

I'm having trouble getting my head around whether or not i need to use an array to generate and then pass back the values in the form.  If that's the case, how would i go about it?

 

If not... what's the best way to achieve this?

 

Thanks guys!

Link to comment
Share on other sites

I'm having trouble getting my head around whether or not i need to use an array to generate and then pass back the values in the form.

 

Pretty much. You should name the checkboxes as an array, and most likely use a unique ID as the key for the array. Consider the following example where we're selecting names and ids from a table and we're going to check which ones we want to delete:

 

<?php
$sql = "SELECT * FROM yourtable";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
while($row=mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo $name.'<input type="checkbox" name="delete['.$id.']" /><br />";
}
?>

 

When you submit this form, $_POST['delete'] will be an array. It will be an array containing keys of all the id's we wish to delete.  In this case, that's not actually that helpful - we'd be better off having the value of each element of the array being the ID, which we could then implode the array and use an IN clause to delete. However, if you have a play with that sort of thing, you should get the general idea.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.