mySQL Query Error in wordpress

I have this code:

add_action( 'delete_post', 'my_delete_function' );
 function my_delete_function($post_id) { 
    global $wpdb;
    $achievement = get_the_category($post_id); 
    $h = $achievement[0]->cat_ID; 
    $s = ''.str_replace('"', '', $h);
    $p = var_dump(htmlentities($s));
   $wpdb->query("INSERT INTO ".$wpdb->prefix."votes (post, votes, guests, usersinks, guestsinks) VALUES('', ".$p.", '', '', '') ") or die(mysql_error());
}

mySQL keeps throwing this error

Read More
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '', '', '')' at line 1

Ive ran the same query in phpMyAdmin, replacing the php vars with values and it works fine

Additionally, ive made sure the the value of $s is just a number by using the echo function on a blank page.

Any help is appreciated

Related posts

Leave a Reply

4 comments

  1. If you want to get the last error and last query you can use this properties of $wpdb object:

    $wpdb->last_error 
    

    will show you the last error, if you got one.

    $wpdb->last_query 
    

    will assist you with showing the last query (where the error occurred)

    I hope this will help you out.

  2. maybe
    $wpdb->query("INSERT INTO ".$wpdb->prefix."votes (post, votes, guests, usersinks, guestsinks) VALUES('', '".$s."', '', '', '') ") or die(mysql_error());

  3. My guess is that the $s is empty and the SQL query ends up looking like this:

    VALUES('', , '', '', '')  
    

    Why are you doing

    $s = str_replace('"', '', $h);
    

    Is it actually possible that the int contains an “? This is not nice. But I’d eventually do this

    $s = (int)str_replace('"', '', $h); 
    

    to ensure that the variable is an int – no matter what.

  4. Try this:

    global $wpdb;
    $achievement = get_the_category($post_id); 
    $h = $achievement[0]->cat_ID; 
    $s = str_replace('"', '', $h);
    $wpdb->query("
        INSERT INTO ".$wpdb->prefix."votes (votes) 
        VALUES ('".$s."');") or die(mysql_error());
    

    If that doesn’t work then you are probably leaving blank fields that require a value.