wpdb在'where子句'错误中的SQL未知列'username'

时间:2014-02-13 07:14:16

标签: php mysql sql wpdb

我一直试图解决为什么我的查询不会从我的表中返回任何结果。我的表名是wp_user_orders。列user_name在该表中。准备和查询返回空数组。查询内部的get结果返回数据库错误。

PHP:

<?php 
    $dirName1 = 'C:/wamp/www/c2c/wp-content/themes/flawless-v1-01';
    $dirName2 = 'C:/wamp/www/c2c';
    require_once($dirName1.'/config/setup.php');
    require_once($dirName2.'/wp-config.php');
    require_once($dirName2.'/wp-load.php');
    require_once($dirName1.'/include/function/encryption-class.php');
    require_once($dirName1.'/include/function/price-calculations.php');

    define('WP_DEBUG', true);
    $wpdb->show_errors();
    $tableName = $wpdb->prefix . "user_orders";
    $user = wp_get_current_user();
    $userId = $user->ID;
    $userName = $user->user_login;
    echo $tableName . ':  ' . $userId . ': '. $userName; 
    echo var_dump($tableName); 
    echo var_dump($userId); 
    echo var_dump($userName); 
    $myQuery = $wpdb->prepare("SELECT * FROM $tableName WHERE user_name = %s", $tableName, $userName);
    $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM %s WHERE user_name = %s", $tableName, $userName), ARRAY_A);
    $results2 = $wpdb->get_results($wpdb->query("SELECT * FROM $tableName WHERE user_name = $userName"));
    print_r($results2);
    echo var_dump($results2);
    print_r($results);
    echo var_dump($results);

    $wpdb->print_error;


?>

我的php显示:

 wp_user_orders: 2: kronus

string 'wp_user_orders' (length=14)

int 2

string 'kronus' (length=6)

WordPress database error: [Unknown column 'kronus' in 'where clause']
SELECT * FROM wp_user_orders WHERE user_name = kronus

null

Array ( )

array (size=0)
  empty

我有一种感觉,我只是错过了一些明显的东西,但我很难过。

更新:

更新了错误的预备声明。

一个:

$wpdb->prepare("SELECT * FROM $tableName WHERE `user_name` = %s", $tableName, $userName)

新:

$wpdb->prepare("SELECT * FROM %s WHERE `user_name` = %s", $tableName, $userName)

更改时出现新错误:

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 ''wp_user_orders' WHERE `user_name` = 'kronus'' at line 1]
SELECT * FROM 'wp_user_orders' WHERE `user_name` = 'kronus'

1 个答案:

答案 0 :(得分:0)

您不是引用用户名或使用变量准备查询,我建议这样做

$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $tableName WHERE user_name = %s",$username));