首页 文章

php codeigniter MySQL搜索查询

提问于
浏览
1

我想在MySQL数据库上创建一个搜索查询,该查询将包含从用户输入的5个不同的字符串 . 我想用这些字符串查询5个不同的表列 .

例如,我有输入字段,如:

名字,姓氏,地址,邮编,城市 .

我应该如何查询我不总是得到所有行的数据库 .

我的查询是这样的:

SELECT user_id, username
from users
where
a like %?% AND
b like %?% AND
c like %?% AND
d like %?% AND
e like %?%;

当我交换AND为OR时,我总是得到所有有意义的结果,当我使用AND时,我只获得完全匹配...

是否有任何功能或陈述可以帮助我解决这个问题?

EDIT

我使用的代码是:

$sql = "select users.user_id, first_name
    from users
    inner join user_normal_aos
    on users.user_id = user_normal_aos.user_id
    inner join normal_areas_of_expertise
    on user_normal_aos.normal_areas_of_expertise_id = normal_areas_of_expertise.normal_areas_of_expertise_id
    where 
    users.first_name like ? AND
    users.kanzlei like ? AND
    normal_areas_of_expertise.normal_aoe like ? AND
    users.postcode like ? AND
    users.city like ?";

    $query = $this->db->query($sql,
        array(
            '%'.$lawyer_name.'%',
            '%'.$kanzlei.'%',
            '%'.$area_of_expertise.'%',
            '%'.$post_code.'%',
            '%'.$city.'%')
        );

1 回答

  • 0

    例如,使用PHP根据您输入的字段调整查询 .

    $where = array();
    $replacements = array();
    /* you can also compare if string is not null or not empty...
       this is just example using isset */
    if (isset($lawyer_name)) {
        $where[] = 'users.first_name like ?';
        $replacements[] = '%'.$lawyer_name.'%';
    }
    
    /* repeat this if again for all your fields .... */
    
    $sql = "..... where ".implode(' AND ', $where);
    
    $query = $this->db->query($sql,
        $replacements
    );
    

相关问题