简体   繁体   中英

Undefined index warning on PDO::fetchAll index

I'm having an awful time trying to track down the cause of this since there are so many different potential causes for an "Undefined Index" warning.

Notice: Undefined offset: 0 in D:\xampp\htdocs\inc\php_main.php on line 71

The line $singleresult = $result[0]; is line 71. I'm positive $result[0] is set, as I've verified it both with print_r and with an isset check. Am I missing something? I'm sort of hoping I just need a sanity check here. :)

function execute ($sql, $bindingsarray) {
    $pdostmt = $this->db->prepare($sql);
    $pdostmt->execute($bindingsarray);
    $result = $pdostmt->fetchAll(PDO::FETCH_ASSOC);
    print_r($result);
    if (isset($result[0]) && isset($result[1])); {
        $singleresult = $result[0];
        return $singleresult;
    }
    return $result;
}

Your variable is not set and you don't notice that because your if line is wrong:

if (isset($result[0]) && isset($result[1])); {
                                           ^ your problem
    $singleresult = $result[0];
    return $singleresult;
}

Is the same as:

if (isset($result[0]) && isset($result[1])) {

}
$singleresult = $result[0];
return $singleresult;

because of the ; you put after your condition. Just remove it and the results should be what you expect them to be:

if (isset($result[0]) && isset($result[1])) {

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