1

I have a form on the page. It has too many things like checkboxes and text fields and dropdowns. But when I don't select one of the checkboxes, the PHP page where i catch the form shows me an error.

Example:

The HTML Code:

Checkbox 1<input type="checkbox" name="check1" value="on" />
Checkbox 2<input type="checkbox" name="check2" value="on" />

The PHP Code:

$check1 = $_GET['check1'];
$check2 = $_GET['check2'];

It works fine if both the items are selected and sent in the URL:

localhost/project/checkbox.php?check1=on&check2=on

But when i deselect 1 of them, suppose check2, then the URL is like this:

localhost/project/checkbox.php?check1=on

and it shows me an error - that $check2 is an undefined index.

But I don't want it to show the error if the checkbox is not being selected. I also tried an if statement to check if i'm getting it in the URL but it didn't work.

Is there a way to first check weather the data is being passed in the URL or not? As I don't get the error. Actually the error is not the main thing, as I'm getting right results and I know I can switch off error reporting in php.ini, but thats not what I want to do. I want it to first check if data is coming in?

Thanks...

Arjun Bajaj
  • 1,932
  • 7
  • 24
  • 41

2 Answers2

2

if (isset($_GET['check2']) && !empty($_GET['check2']) will do the check if check2 GET parameter is present and is not empty.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    you can use just !empty($_GET['check2']) – dynamic Mar 21 '11 at 18:27
  • @yes123: That'll fail if that query parameter contains a 0 or a space character. `$x = 0; echo empty($x) ? 'y' : 'n'` will say 'y'. empty is a horribly stupid function. – Marc B Mar 21 '11 at 18:38
0

The checkbox value is only registered, when it's checked. So you can simply do a check like this:

$check1 = isset($_GET['check1']);
$check2 = isset($_GET['check2']);

$check1 and $check2 will now have boolean values:

echo "Checkbox 1 one is " . ($check1 ? "checked" : "not checked") . PHP_EOL;
echo "Checkbox 2 one is " . ($check2 ? "checked" : "not checked") . PHP_EOL;
Czechnology
  • 14,832
  • 10
  • 62
  • 88