if statement doesn't work
In Wordpress, I'm trying to add the post ID of posts I publish in a new table if not already there (to avoid double entries when updating posts from the admin panel)
if( $wpdb->get_row("SELECT post_id FROM wp_post_votes WHERE post_id != $post_ID" ) ) {
$wpdb->insert( $wpdb->prefix . 'post_votes', array( 'post_id' => $post_ID ) );
}
This statement works only with a = operator and an "else ( do code.. }". 开发者_Python百科With != nothing happens I can't figure out why.. I just want to keep the code as short as possible.
if(!($wpdb->get_row("SELECT post_id FROM wp_post_votes WHERE post_id = $post_ID" ) ) ) {
$wpdb->insert( $wpdb->prefix . 'post_votes', array( 'post_id' => $post_ID ) );
}
Should be what you're looking for. (Added a ! before the conditional to simulate your "else" effect)
Try
if( !$wpdb->get_row("SELECT post_id FROM wp_post_votes WHERE post_id = $post_ID" )
Your if statement is checking that the output from
$wpdb->get_row("SELECT post_id FROM wp_post_votes WHERE post_id != $post_ID" )
evaluates to a true-like value. You're essentially running a query that selects all IDs from ALL rows (except for perhaps one). This is inefficient and probably not what you wanted - you probably wanted to check if a matching row was not found, not that non-matching rows were found.
You probably want:
if (!$wpdb->get_row("SELECT post_id FROM wp_post_votes WHERE post_id = $post_ID" )) {
精彩评论