checkboxes in loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

checkboxes in loop

Post by aceconcepts »

Hi,

I have loop that gets all the records from a table in a database.

I use the following to query the database and extract the data:

Code: Select all

$query = "SELECT * FROM table1";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
extract($row);

display rows
}
At the end of each row fetched from the database i have inserted an html checkbox.

Assume the query returns 10 rows of data and the user 'ticks' 5 checkboxes and clicks the form submit button.

How can I determine which database rows have been 'ticked', as more than one has been ticked?

Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Set the value attribute of each check box to be the id of the record they represent.
blackbeard
Forum Contributor
Posts: 123
Joined: Thu Aug 03, 2006 6:20 pm

Post by blackbeard »

You need to give each checkbox a unique name.

If you're using a loop to display them, then create a unique name in the loop, something like: "myCheckbox_".$i

Then it should be easy to to figure out which one is checked.
visitor-Q
Forum Commoner
Posts: 72
Joined: Mon Feb 05, 2007 1:40 am

Post by visitor-Q »

@blackbeard - feyd's recommendation is similar, but better. even tho your method allows for a unique name for each checkbox, you still need a way to affilliate that checkbox with a specific row in the database. this is where feyd's suggestion overcomes yours. i think he meant something like this:

Code: Select all

$query = "SELECT * FROM table1";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
        echo "<input type=\"checkbox\" name=\"{$row['id']}\">\n";

}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

No. I said value.

Code: Select all

<input type="checkbox" name="selection[]" value="1234" />
Post Reply