Arjun Bajaj
Arjun Bajaj

Reputation: 1962

How to check weather the $_GET is being received or not? (PHP)

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...

Upvotes: 1

Views: 238

Answers (2)

Czechnology
Czechnology

Reputation: 14992

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;

Upvotes: 0

anubhava
anubhava

Reputation: 784938

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

Upvotes: 2

Related Questions