1

I have a custom table called wpgrating

I have a column there called "ip"

Now what I want to do is search for "ip" column and see if there is an entry already there?

How can I achieve this?

3
  • In a WP template, plugin, PHPMyAdmin or from where are you trying to achieve this? What have you tried so far?
    – jdm2112
    Commented Jun 13, 2014 at 15:28
  • Are you trying to retrieve the whole column? Or just the value in that column (including whether or not it exists) for a specific given row? Commented Jun 13, 2014 at 16:06
  • For now I am using it in template for now but its actually will be used in plugin. .I will check solutions and will update here.. Commented Jun 14, 2014 at 16:37

2 Answers 2

1

What you are asking for should be straight SQL.

Try adapting the following:

function check_for_ip($ip) {
    global $wpdb;
    $sql = <<<SQL
        SELECT true
        FROM `wpgrating`
        WHERE `ip` = %s
SQL;
    return (bool) $wpdb->get_var($wpdb->prepare($sql, $ip));
}

In essence, we do a simple SELECT with the IP in question as in the WHERE clause. (Note that it's important that we don't use the otherwise standard SELECT 1 as WordPress' database abstractor will always return false for that.) Because we are not selecting an entire row, we avoid a lot of overhead..

0

Hope this helps

global $wpdb;
$ip = "120.0.0.1"

$ip_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM wpgrating WHERE ip LIKE %s", $ip));

if($ip_row)
    return "IP exists";
else
    return "IP does not exist";

Its pretty straight forward but still this is whats going on. What I understand from the question is that the user wants to find out, if an ip address already exists in the database. Using the $wpdb class we search for the specific IP address. If it exists it would return an object containing the full row for that IP. If not, $ip_row would be empty.

3
  • An answer should not be raw code dump. Please add more explanation and see How to Answer
    – s_ha_dum
    Commented Jun 14, 2014 at 0:58
  • That is not correct/safe use of prepare() method.
    – Rarst
    Commented Jun 14, 2014 at 16:37
  • @Rarst Yes it would probably throw a warning with the current version of WordPress. I have fixed it.
    – Atif
    Commented Jun 14, 2014 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.