简体   繁体   中英

PHP script error Notice: Undefined variable

I am writing a PHP script for advanced searching but an error occurred. Please help
Code:

$key    = $_GET['key'];
$auth   = $_GET['auth'];
$lang   = $_GET['lang'];
$pub    = $_GET['pub'];

if(isset($key) OR isset($auth) OR isset($lang) OR isset($pub))
{
    if ($key    != NULL){$keyword   = "AND (native_name LIKE '%".$key."%' OR unique_name LIKE '%".$key."%')";}
    if ($auth   != 0)   {$auther    = "AND auth_id=".$auth."";}
    if ($lang   != 0)   {$language  = "AND lang_id=".$lang."";}
    if ($pub    != 0)   {$publisher = "AND pub_id=".$pub."";}

    $search_query = "SELECT native_name from books WHERE status=1 ".$keyword." ".$auther." ".$language." ".$publisher."";
    print $search_query;
}

Error:

Notice: Undefined variable: keyword in FILE_PATH on line 90
Notice: Undefined variable: auther in FILE_PATH on line 90
Notice: Undefined variable: language in FILE_PATH on line 90
Notice: Undefined variable: publisher in FILE_PATH on line 90

If you are creating variables through if statements then there is a likelihood that these variables won't be created.

There are a couple of different options in your case.

1, Use Ternary syntax

$keyword = $key != NULL ? "AND (native_name LIKE '%".$key."%' OR unique_name LIKE '%".$key."%')" : "";
$author = $auth !=0 ? "AND auth_id=".$auth : "";
$language = $lang !=0 ? "AND lang_id=".$lang : "";
$publisher = $pub !=0 ? "AND pub_id=".$pub : "";

2, Predefine your variables

$keyword = "";
$author = "";
$language = "";
$publisher = "";

if ($key    != NULL){$keyword   = "AND (native_name LIKE '%".$key."%' OR unique_name LIKE '%".$key."%')";}
if ($auth   != 0)   {$auther    = "AND auth_id=".$auth."";}
if ($lang   != 0)   {$language  = "AND lang_id=".$lang."";}
if ($pub    != 0)   {$publisher = "AND pub_id=".$pub."";}

$keyword/$auther/etc.. only get assigned if the corresponding value in _POST is set. If no data is passed in, $key/$auth/etc... will be empty strings or null, which will be equal to 0/null. Try:

if ($key != null) {
   $keyword = ...;
} else {
   $keyword = some default value;
}

and similarly for the other ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM