Home > Software design >  How to avoid PHP Warning for Undefined Offset in wp-db.php using foreach
How to avoid PHP Warning for Undefined Offset in wp-db.php using foreach

Time:09-26

I'm attempting to set a cookie containing a post ID, but only when the current post ID isn't present in a table. The code works, but I'm getting a PHP warning "Undefined offset: 0" from wp-includes/wp-db.php and I'm wondering what I've done wrong.

function getFromDatabase() {
    global $wpdb;
    $sql = $wpdb->prepare( "SELECT page_id FROM foo WHERE page_id IS NOT NULL" );
    $result = $wpdb->get_results( $sql );
    $resultsArray = array();
    foreach ( $result as $row ) {
        $resultsArray[] = $row->page_id;
    }
    return $resultsArray;
}

...

$currentPID = get_the_id();
$ignoredPIDs = getFromDatabase();
if ( !in_array($currentPID, $ignoredPIDs) ) {
    // Set a cookie to post ID
}

I should mention that the DB query will always return at least one result. Any thoughts on this would be greatly appreciated.

Update - Found the problem, it was the call to $wpdb->prepare. It's just a guess, but nothing needed preparing, everything is hard-coded, and perhaps it was complaining about that.

CodePudding user response:

Without being able to see what's in getFromDatabase:

I know you said that the DB query will always return at least one result but just for the heck of it, try to check for empty. If this works then your problem is obviously in the getFromDatabase function.

$currentPID = get_the_id();
$ignoredPIDs = getFromDatabase();
if(!empty($ignoredPIDs)) {
  if ( !in_array($currentPID, $ignoredPIDs) ) {
      // Set a cookie to post ID
  }
}
  • Related