$wpdb->get_results($query); Returns NULL with variable $query - Same query works hardcoded

筅森魡賤 提交于 2020-01-06 11:48:55

问题


I've been trying to debug this script for a month. The rest of the program is already built and this one thing just will not work. The issue is the $query variable, it returns null unless I hard code - which isn't possible with a search form. I've tried adding '\n', I've tried just putting in the returns, I've changed the " to ' for the beginning. I've tested the rest of the code outside of this block and it all works. I've run tests on this block as you can see from commented out echo statements below. Those all test fine. The $query string built by the function returns the correct data when hard coded or in the database browser. I'm stuck! Help please.

[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]

来源:https://stackoverflow.com/questions/19215374/wpdb-get-resultsquery-returns-null-with-variable-query-same-query-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!