在表单中,没有输入是强制性的。所以,我希望在wpdb查询中有一个动态的“where”子句。
目前这是查询:
$data = $wpdb->get_results($wpdb->prepare("SELECT * FROM
`wp_gj73yj2g8h_hills_school_data` where
`school_zipcode` = %d AND `school_type` = %s AND `school_rating` = %s
;",$selectedZip,$selectedType,$selectedRating));
如果用户只输入school_zipcode,那么where子句应该只有“school_zipcode”列。 其他组合的方式相同。
答案 0 :(得分:1)
我不会在动态where子句中使事情变得复杂......我会编写创建查询的PHP代码。例如......
请注意!这个代码没有在服务器上测试,它只是一个想法如何解决问题!
<?php
$where_query = array();
// Make sure to escape $_POST
if (!empty($_POST['school_zipcode')) {
$where_query[] = "school_zipcode='" . $_POST['school_zipcode'] . "'";
}
// Make sure to escape $_POST
if (!empty($_POST['school_type')) {
$where_query[] = "school_type='" . $_POST['school_type'] . "'";
}
// Should result in WHERE school_zipcode='123' AND school_type='text'
$where_query_text = " WHERE " . implode(' AND ', $where_query);
$data = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_gj73yj2g8h_hills_school_data` " . $where_query_text . ";"));