Support » Fixing WordPress » How To Handle MySQL-Errors With WPDB-Class?

  • Resolved saphod

    (@saphod)


    Hi,

    I wonder how I can find out if my MySQL query led to an error.

    I am using a function like this:

    function block_ip($ip) {
    	$query = "INSERT IGNORE INTO wp_blocked_ips (ip) VALUES ('$ip')";
    	$wpdb =& $GLOBALS['wpdb'];
    	return $wpdb->get_results($query);
    }

    Then, I tried to call it like this:

    $blocked = block_ip('123.456.789.012');
    if ($blocked) {
    	echo "Everything went fine.";
    } else {
    	echo "An error has occured!";
    }

    But somehow, this is not working, as $blocked always seems to be true, even if there was an error with the query.

    How can I handle an error resulting from a MySQL query?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter saphod

    (@saphod)

    OK, in “Popularity Contest”, I found this:

    if (count($items) > 0) { ... }

    where $items is the query result.

    This will probably only work if the query returns no elements, which is not similar with an error, right?

    I have also tried

    if(!(empty($results))) { ... },

    meaning that an error occured when the result is empty, but that won’t work, either.

    Anyone, please?

    Thread Starter saphod

    (@saphod)

    Ooops… just found out that $wpdb->query() returns FALSE in case of an error, not $wpdb->get_results()…

    Thread Starter saphod

    (@saphod)

    This seems to work:

    Function:
    =========

    function block_ip($ip) {
          global $wpdb;
          $query = "INSERT IGNORE INTO wp_blocked_ips (ip) VALUES ('$ip')";
          if ($wpdb->query($query) === FALSE) {
               return FALSE;
          } else {
               return $wpdb->get_results($query);
          }
     }

    Call:
    =====

    $blocked = block_ip('123.456.789.012');
    
     if (!($blocked === FALSE)) {
         echo "Everything went fine.";
     } else {
         echo "An error has occured!";
     }
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How To Handle MySQL-Errors With WPDB-Class?’ is closed to new replies.