为什么MySQLi通过LIKE操作返回重复结果?

时间:2019-05-12 07:16:20

标签: php

我想在数据库中搜索member的关键字,我使用下面的代码搜索它,但是它返回6个结果,而它只匹配数据库中的2行。

代码如下:

    $mysqli = new mysqli('host', 'root', 'pw', 'db_name');
    function searchMember($keyword)
    {
        $keyword = trim($keyword);
        if (!empty($keyword)) {
            $keyword = '%'.$keyword.'%';
            $member_query = 'SELECT display_name,username,email,is_admin FROM user WHERE display_name LIKE ? OR username LIKE ? OR email LIKE ?';
            $member_stmt = $connectdb->stmt_init();
            $member_stmt->prepare($member_query);
            $member_stmt->bind_param('sss', $keyword, $keyword, $keyword);
            $member_stmt->execute();
            $member_stmt->store_result();
            $member_stmt->bind_result($display_name, $username, $email, $is_admin);
            if ($member_stmt->num_rows > 0) {
                $members[] = $member_stmt->fetch(MYSQLI_ASSOC);
                return $members;
            } else {
                return false;
            }
            $member_stmt->free_result();
        } else {
            return false;
        }
    }

    $result = searchMember('car');

    var_dump($result);

我认为问题出在每行有多个匹配字符串,例如usernameemail,它们都包含关键字car,但我仍然没有不知道如何解决

编辑:现在,我解决了重新分配问题,唯一的问题是,为什么总是在结果中添加NULL值?
像这样:

Array ( 
    [0] => Array ( 
        [uid] => 1 
        [username] => carry
        [email] => carry@gmail.com 
        [is_admin] => true ) 
    [1] => Array ( 
        [uid] => 2 
        [username] => carryaa
        [email] => carryaa@gmail.coma 
        [is_admin] => false ) 
    [2] => 
)

它总是将[2]添加到数组,在var_dump中显示如下:

array(3) { 
    [0]=> array(4) { 
        ["uid"]=> int(1) 
        ["username"]=> string(9) "carry" 
        ["email"]=> string(19) "carry@gmail.com" 
        ["is_admin"]=> string(4) "true" 
    } 
    [1]=> array(4) { 
        ["uid"]=> int(2) 
        ["username"]=> string(10) "carryaa" 
        ["email"]=> string(20) "carryaa@gmail.coma" 
        ["is_admin"]=> string(5) "false" 
    } 
    [2]=> NULL 
}

0 个答案:

没有答案