Checking variables in $POST

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
gigowiz
Forum Newbie
Posts: 2
Joined: Thu Jun 12, 2008 6:25 pm

Checking variables in $POST

Post by gigowiz »

I have a form that lists a variable number of records. I number them 1 through n. I also conatenate the number to the form field names. For example, the records have the field chk (for the checkbox), name, date and event fields. The form field names are chk1, name1, date1, event1...chkn, namen, daten, eventn. The user ticks the checkbox(es) for the records he wants to delete and clicks the Submit button sending the form field data to another PHP script. It also sends the total number of records that were displayed. The receiving script loops through the received form fields. If the checkbox was ticked, e.g., if they selected record 5 then the field chk5 will exist, I get the corresponding fields, name5 etc., and create the SQL delete statement.

for ($i=1; $i<=$nbr_records; $i++){
$chk_nbr = "chk";
$chk_nbr .="$i";
if (isset ($_POST['${$chk_nbr}'])) {
....
}

Now to my question. How do I evaluate the variable in the "isset" so I can see if the form field 'chkn' (where n can be any number) is set?

Or maybe there's a better way to do this?

Thanks
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Checking variables in $POST

Post by Ambush Commander »

Because field names are text, there's no need to use variable variables. To check for the existence of "chk$n" where $n is the number, all you need to do is isset($_POST["chk$n"]). It's that simple.
hansford
Forum Commoner
Posts: 91
Joined: Mon May 26, 2008 12:38 am

Re: Checking variables in $POST

Post by hansford »

and in case isset() confuses you. its used to check if a variable has been set with a value.

if(isset($_POST["chkn"])){
// variable $_POST["chkn"] has a value

$myvar = $_POST["chkn"]; //assign value to $myvar

echo $myvar;
}
gigowiz
Forum Newbie
Posts: 2
Joined: Thu Jun 12, 2008 6:25 pm

Re: Checking variables in $POST

Post by gigowiz »

Thank you very much. Works great!
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Checking variables in $POST

Post by RobertGonzalez »

isset() returns true for any value that has been given a value other than null. Be watchful with this function as it can sometimes give you unexpected results (especially in cases where you set a variable value to null and check to see if it is set).
Post Reply