get_results($wpdb->prepare("-6ren">
gpt4 book ai didi

php - wpdb-> 准备查询中的动态 "Where"子句

转载 作者:行者123 更新时间:2023-11-28 23:20:39 27 4
gpt4 key购买 nike

在表单中,没有任何输入是强制性的。所以,我想在 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”列。其他组合方式相同。

最佳答案

我不会用动态 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 . ";"));

关于php - wpdb-> 准备查询中的动态 "Where"子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41765116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com