$ wpdb-> get_results($查询);使用变量$ query返回NULL - 相同的查询工作硬编码

时间:2013-10-07 00:00:24

标签: php mysql wordpress wpdb

我一直在尝试调试这个脚本一个月。程序的其余部分已经构建完毕,这一件事情无法正常工作。问题是$ query变量,它返回null,除非我硬编码 - 这对于搜索表单是不可能的。我已经尝试添加'\ n',我已经尝试过放入返回,我已经将“改为”改为开头。我已经测试了这个块之外的其余代码了,一切正常。我在这个块上运行测试,你可以从下面注释掉的echo语句中看到。那些都测试正常。函数构建的$ query字符串在硬编码时或在数据库浏览器中返回正确的数据。我被卡住了!请帮助。

[code snippet]

if(isset($_POST['submit'])) {

    // define the list of fields
    $fields = array('lastname', 'firstname', 'dob', 'city', 'telephone', 'email', 'user_id');
    $conditions = array();


    // loop through the defined fields
    foreach($fields as $field){
        //echo "Field is ".$field."\n";
        // if the field is set and not empty
        if(isset($_POST[$field]) && $_POST[$field] != '') {
              //echo "Field is: ".$field."\n".$field." is: ".$_POST[$field]."\n";            
            // create a new condition while escaping the value inputed by the user (SQL Injection)
            $conditions[] = "$field LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%' 
            ";
        }
    }

    // builds the query
    $query = "\"
    SELECT * 
    FROM wp_ct_ad_client_db_table
    ";

    // if there are conditions defined
   $query_user_id = "user_id = ".$user_id."
   \"";
    array_push($conditions, $query_user_id);

    if(count($conditions) > 0) {
        // append the conditions
        $query .= "WHERE " . implode(' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
    }

    echo "Query String: ".$query."\n";

    //$result = $wpdb->get_results($query);
    $my_query = $query;

    echo "Test My Query Logic \n";
    //$result = $wpdb->get_results("SELECT * FROM wp_ct_ad_client_db_table WHERE lastname LIKE '%A%' AND user_id = $user_id;");
    //$result = $wpdb->get_results($my_query);
    $result = $wpdb->get_results($my_query, A_ARRAY);

    var_dump($result);

[/ code snippet]

0 个答案:

没有答案