0

我一直在浏览 WordPress Codex,似乎我的语法是正确的,但我似乎无法追查为什么我在errors.text与下面代码相关的文件中不断出现一行一行的错误,这是为了WordPress 简码:

function blahblah_display_referrer() {
    global $wpdb, $user_ID;

    // Logged in user
    if ( is_user_logged_in() == true ) {
        $sql = "SELECT display_name FROM " .$wpdb->prefix. "users WHERE ID=".$user_ID;
        $ref = $wpdb->get_var($wpdb->prepare($sql));
        return 'Welcome Back: '.$ref;
    }

    // Visitor message with cookie or without...
    $ref = $_COOKIE['ref'];         
    $sql = "SELECT display_name FROM " .$wpdb->prefix. "users WHERE ID=".$ref;
    $ref = $wpdb->get_var($wpdb->prepare($sql));
    if ( !isset($ref) ) {
        return 'Welcome Visitor';
    }

    return 'Referred By: '.$ref;
}

正如我之前所说,这段代码可以完美执行,没有任何问题。它只显示以下错误:

[10-Jul-2012 15:10:45] WordPress database error 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 for query SELECT display_name FROM wp_users WHERE ID= made by 
require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), 
include('/themes/kaboodle/index.php'), get_sidebar, locate_template, load_template, 
require_once('/themes/kaboodle/sidebar.php'), woo_sidebar, dynamic_sidebar, 
call_user_func_array, WP_Widget->display_callback, WP_Widget_Text->widget, 
apply_filters('widget_text'), call_user_func_array, do_shortcode, preg_replace_callback, 
do_shortcode_tag, call_user_func, blahblah_display_referrer

这是我的服务器信息:

Apache version  2.2.21
PHP version     5.2.17
MySQL version   5.1.63-cll
Architecture    x86_64
Operating system    linux
4

2 回答 2

0

我也遇到过同样的问题,答案在错误中,但并不明显。每当有人访问该页面时,无论他们是否有 cookie,您都会运行 Ref 查询。当您进行测试时,您很可能使用 cookie 进行测试,因此它不会产生错误。但是,当它在没有 cookie 的情况下运行时,它会搜索空白 ID。

我在下面修改了您的代码并评论了这些更改。

// Visitor message with cookie or without...
$ref = $_COOKIE['ref'];         
  /* This section should only run if there is a ref from the cookie
    $sql = "SELECT display_name FROM " .$wpdb->prefix. "users WHERE ID=".$ref;
    $ref = $wpdb->get_var($wpdb->prepare($sql)); */
if ( !isset($ref) || $ref == "" ) { //In case the cookie returns blank instead of null
    return 'Welcome Visitor';
} else { //added this section after the check for $ref so it only runs where there is a ref
    $sql = "SELECT display_name FROM " .$wpdb->prefix. "users WHERE ID=".$ref;
    $ref = $wpdb->get_var($wpdb->prepare($sql));
}    
return 'Referred By: '.$ref;

希望这可以帮助。

于 2013-03-21T19:18:01.887 回答
0

It would seem that Wordpress's WPDB database module suppresses SQL errors by default.

You can turn error echoing on and off with the show_errors and hide_errors, respectively.

<?php $wpdb->show_errors(); ?>
<?php $wpdb->hide_errors(); ?> 

You can also print the error (if any) generated by the most recent query with print_error.

<?php $wpdb->print_error(); ?>

Could that be the problem?

于 2012-07-10T15:44:54.617 回答