Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
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. –  at least three characters Nov 23 '10 at 14:39
    
@user1613: $voter_ip is a string while $post_id is an integer. –  sorich87 Nov 23 '10 at 14:42
    
Oooh! I should have known that.. –  at least three characters Nov 23 '10 at 14:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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