このスクリプトのデバッグを 1 か月試みました。プログラムの残りの部分は既にビルドされており、この 1 つのことが機能しません。問題は $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);
[/コードスニペット]