This question already has an answer here:
I have some variables which may sometimes be empty and sometimes they may not be...what is the best way to prevent these errors from occurring?
Notice: Undefined variable:
$results = searchOrders($_GET['search'], $_GET['criteriaId'], $_GET['dateEntered'], $_GET['state']);
Anyone of the $_GET can be empty at any time. So the error would pop up a lot
</div>
You need to first validated it with empty function like that.
$search = !empty($_GET['search'])?$_GET['search']:"";
$criteriaId = !empty($_GET['criteriaId'])?$_GET[criteriaId]:"";
$dateEntered = !empty($_GET['dateEntered'])?$_GET['dateEntered']:"";
$state = !empty($_GET['state'])?$_GET['state']:"";
$results = searchOrders($search, $criteriaId, $dateEntered, $state);
check with if(isset($var) && !empty($var))
eg:
if (empty($var) && isset($var)) {
echo '$var is either 0, empty, or not set at all';
}
Common problem, commonly solved with
if(isset($_GET['search'])) {
$results = searchOrders($_GET['search'], $_GET['criteriaId'], $_GET['dateEntered'], $_GET['state']);
}
Now only if search is available it will run.
If you want more info about the isset function look here: http://php.net/manual/en/function.isset.php
foreach($_GET as $key){
if(isset($key)){
$results = searchOrders($key);
}
}
Does your searchOrders
function support null arguments? If so, and you just want to get rid of warning/error messages, just put @
before
$results = @searchOrders($_GET['search'], $_GET['criteriaId'], $_GET['dateEntered'], $_GET['state']);
If your function does not support null arguments and they are all required, you need to check them before
if( isset($_GET['search']) && !empty($_GET['search'])
&& isset($_GET['criteriaId']) && !empty($_GET['criteriaId'])
&& isset($_GET['dateEntered']) && !empty($_GET['dateEntered'])
&& isset($_GET['state']) && !empty($_GET['state']))
$results = searchOrders($_GET['search'], $_GET['criteriaId'], $_GET['dateEntered'], $_GET['state']);
If you are using these variables multiple times, and don't want to use if
or @
everytime, you can check them somewhere on the beginning of the script:
$_GET['criteriaId'] = (isset($_GET['criteriaId']) & !empty($_GET['criteriaId'])) ? $_GET['criteriaId'] : null;
You can use this for all the variables and replace null
with default value that should be assigned to variable.
The quick and dirty way is to use the @
operator:
$results = searchOrders(@$_GET['search'], @$_GET['criteriaId'], @$_GET['dateEntered'], @$_GET['state']);
However I would recommend not to use this, because it leads to bad, sloppy code. You can use isset
for variables or in case of arrays use construct like this:
$vars = $_GET + array(
'search' => '',
'criteriaId' => '',
'dateEntered' => '',
'state' => '',
);
// Alternatively, use $_GET += array(...)
$results = searchOrders($vars['search'], $vars['criteriaId'], $vars['dateEntered'], $vars['state']);