Page 1 of 1

checkboxes in loop

Posted: Mon Mar 19, 2007 1:00 pm
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

Posted: Mon Mar 19, 2007 1:13 pm
by feyd
Set the value attribute of each check box to be the id of the record they represent.

Posted: Mon Mar 19, 2007 1:13 pm
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.

Posted: Mon Mar 19, 2007 2:07 pm
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";

}

Posted: Mon Mar 19, 2007 2:45 pm
by feyd
No. I said value.

Code: Select all

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