我已经尝试调试这个脚本一个月了。程序的其余部分已经构建好了,这一点就行不通了。问题是 $query 变量,除非我硬编码,否则它会返回 null - 这对于搜索表单是不可能的。我试过添加'\n',我试过只输入返回值,我已经将“更改为”一开始。我已经测试了这个块之外的其余代码并且一切正常。我已经在这个块上运行了测试,你可以从下面注释掉的 echo 语句中看到。这些测试都很好。由函数构建的 $query 字符串在硬编码或在数据库浏览器中返回正确的数据。我被卡住了!请帮忙。
[代码片段]
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);
[/代码片段]