Page 1 of 1

Checking variables in $POST

Posted: Thu Jun 12, 2008 6:41 pm
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

Re: Checking variables in $POST

Posted: Thu Jun 12, 2008 8:56 pm
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.

Re: Checking variables in $POST

Posted: Thu Jun 12, 2008 10:44 pm
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;
}

Re: Checking variables in $POST

Posted: Fri Jun 13, 2008 10:21 am
by gigowiz
Thank you very much. Works great!

Re: Checking variables in $POST

Posted: Fri Jun 13, 2008 11:23 am
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).