while语句中的逻辑

时间:2014-04-18 19:11:11

标签: php sql pdo while-loop

对于搜索我正在使用此代码段:

$stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
    $keyword = "%".$data."%";
    $stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
    $stmt->execute();   
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $row_array['id'] = $row['id'];
        $row_array['user'] = utf8_encode($row['username']);
        array_push($return_arr,$row_array);
    } 

我没有得到那些“LIKE关键字”的值,而是从我的表“users”得到每一个结果,为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

在准备查询之前,您应该检查$ data是否为空:

if(!empty($data) && is_string($data)){
    $stmt = $dbh->prepare('SELECT id,username FROM `users` WHERE `username` LIKE :keyword');
    $keyword = "%".$data."%";
    $stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
    $stmt->execute();   
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $row_array['id'] = $row['id'];
        $row_array['user'] = utf8_encode($row['username']);
        array_push($return_arr,$row_array);
    }
} else {
    // Do something else
}