2

Part of a voting script I'm working on: I'm checking a custom table in my WP database to see if a user already voted for a post by checking the IP address and the post id.

If the user's IP already exists for the post they voted, I want to echo "Already voted!" otherwise add the IP. This is what I came up with..

global $wpdb;
$voter_ip = $_SERVER['REMOTE_ADDR']; 
$post_id = $_POST['post_id'];

if (!($wpdb->get_row("SELECT voter_ip FROM wp_voter_ips WHERE post_id = $post_id AND voter_ip = $voter_ip") ) ) { //if IP address for matching post id not found in wp_voter_ips table
$wpdb->insert( $wpdb->prefix . 'voter_ips', array( 'post_id' => $post_id, 'voter_ip' => $voter_ip ) ); //add IP and post_id
echo "voted!";
}
else //if IP already exists
{
echo "Already voted!";
}

I triple checked to make sure the variables and column names are correct. Regardless of the if statement, it inserts the voters IP even when it already exists.

1 Answer 1

4

On your if(), it should be like this:

if (!($wpdb->get_row("SELECT voter_ip FROM " . $wpdb->prefix . "voter_ips WHERE post_id = $post_id AND voter_ip = '$voter_ip'")

Notice the quotation mark added on $voter_ip.

3
  • that did it! I hope you don't mind me asking but I'm very curious why quotation marks make a difference? I don't use them for $post_id and it works fine. In fact I haven't use them in any of my queries without problems. Commented Nov 23, 2010 at 14:39
  • @user1613: $voter_ip is a string while $post_id is an integer. Commented Nov 23, 2010 at 14:42
  • Oooh! I should have known that.. Commented Nov 23, 2010 at 14:53

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.