2012-01-08 67 views
0

MySQL查询错误我有这样的代码:在WordPress

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总是抛出此错误

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 

伊夫跑在phpMyAdmin相同的查询,取代了PHP和值VAR和它工作正常

另外,通过在空白页上使用echo函数,我确信$ s的值只是一个数字。

任何帮助表示赞赏

+0

在最后一行之前添加一个'var_dump($ s);'来检查你输出的内容。如果它包含HTML,请使用'var_dump(htmlentities($ s));' – 2012-01-08 11:39:36

+0

您能显示完整的最终查询吗? – 2012-01-08 11:41:32

+0

检查您的单引号实际上是单引号而不是反引号。还要替换$ s。与。(int)$ s。只想确认一下。 – 2012-01-08 11:42:15

回答

3

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

+0

这样做伎俩谢谢。 – 2012-01-08 11:49:35

0

试试这个:

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()); 

如果不工作,那么你很可能留下需要的值空白字段。

1

我的猜测是,$ s是空的,SQL查询最终看起来像这样:

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

你为什么要这么做

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

它实际上是可能的INT包含“?这是不好的,但我最终会这样做

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

确保该变量是一个int - no 有什么关系。

3

如果你想获得最后的错误和最后一个查询可以使用WPDB $对象这个属性:

$wpdb->last_error 

会告诉你过去的错误,如果你有一个。

$wpdb->last_query 

将为您提供展示我希望这将帮助你的最后一个查询(发生错误)