WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How To Handle MySQL-Errors With WPDB-Class? (4 posts)

  1. saphod
    Member
    Posted 6 years ago #

    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?

  2. saphod
    Member
    Posted 6 years ago #

    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?

  3. saphod
    Member
    Posted 6 years ago #

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

  4. saphod
    Member
    Posted 6 years ago #

    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!";
     }

Topic Closed

This topic has been closed to new replies.

About this Topic