当代码完美执行时,SQL查询在错误日志中显示错误


SQL Query Showing Errors In Error Log While Code Executes Flawlessly

我一直在浏览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

看起来Wordpress的WPDB数据库模块默认情况下会抑制SQL错误。

您可以使用show_errors和分别为hide_errors。

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

您还可以打印最近带有print_error的查询。

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

这可能是问题所在吗?

我也遇到过同样的问题,答案在错误中,但并不明显。每当有人访问页面时,无论他们是否有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;

希望这能有所帮助。