You are here: Re: Iterate Through Values from All Checked Checkboxes « All PHP « IT news, forums, messages
Re: Iterate Through Values from All Checked Checkboxes

Posted by no on 12/11/06 09:38

On 11 Dec 2006 00:15:44 -0800, "ameshkin" <amir.meshkin@gmail.com>
wrote:

>What I want to do is very simple, but I'm pretty new at PHP and its a
>little hard for me.
>
>I have one page, where there are a rows of checkboxes. A button
>selects all checkboxes, and then presses delete.
>
>When delete is pressed, I want to go to a next page and run a sql
>command for every single box thats checked. The checkboxes store a
>value, and multiple boxes can be checked.
>
>On the second page, whch is the form actin, I simply want to iterate
>through and pull which values are checked and run a sql command for
>each value.
>
>I have no idea how to do this. I assume you willl have to use a for
>each statement, but am having trouble programming this.

It's quite easy:

The checkboxes should be an array so in your HTML give them a name
like name="cbox[]" (note you do not put numbers in the brackets - all
the checkboxes will just be called "cbox[]").

Then set the value to the unique ID or value that your SQL needs to do
the updating. The classic usage would be to list a load of rows in a
table and set the checkbox ID to the table row ID.

Then in your action code you will just be passed $_POST['cbox'][]
(assuming you are using the post method) which will contain only those
checkboxe values that were ticked - so don't bother looking for the
blank ones ;o) Examine the foreach() looping command to simply loop
through each in turn.

However, the clever play for this situation is to actually create one
SQL command in the loop and then execute it afterwards - so reducing
the load in the database. So something like this (untested):

for ( $i=0 ; isset($_POST['cbox'][$i]) ; $i++ ) {
$id = mysql_escape_string($_POST['cbox'][$i];
if (!$i) {
$sql = 'delete from widgets where id="'.$id.'";
} else {
$sql .= ' or id="'.$id.'";
}
}
// now run your sql command here

We need to identify the first loop iterration, hence the use of $i and
checking for it's first value (0). Also, note that we run
mysql_escape_string() on all values passed from the form to remove any
injected sql code - because we don't trust *anything* the users have
typed! :o)

Chris R.

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация