Search code examples
phpsqlnotice

php notice, sql and isset()


how can i get rid of the apache/php message "Notice: Undefined index" in an sql query string:

Using @ it works $query .= " hash = '" . @$_GET['key'] . "'";

but with isset() it doesn't: $query .= " hash = '" . !isset($_GET['key']) . "'";

and at the if clause:

Using @ it works if (@$_GET['action'] === "de") {

but with isset() it doesn't: if (!isset($_GET['action']) === "de") {

Thanks for your help


Solution

  • The @ operator just tells the interpreter to shut up and ignore errors that will not crash the system. It gives an unstable code, and should not be used!

    The function isset returns trueor false. You use it to check if a variable is declared and has a value. This is how you should use it:

    $query .= "hash = '" . ( isset($_GET['key']) ? $_GET['key'] : '' ) . "'";
    

    This means use $_GET['key'] if it is declared and has a value otherwise use the default value ('').

    Sometimes the code can run with a default value, if nothing is supplied. This is one use of isset().

    Above, I use a short version of if ... else. The two statements below are the same:

    // Short version ( TEST ? if TRUE : else FALSE )
    $query = isset($_GET['key']) ? $_GET['key'] : '';
    
    // Long version
    if ( isset( $_GET['key'] ) )
        $query = $_GET['key'];
    else
        $query = '';