PDO中的LIKE查询无法正常工作

时间:2014-09-05 15:02:44

标签: php mysql pdo

PDO查询运行正常,但是当我尝试使用LIKE查询时,它不起作用并给出错误。我知道我做错了,如果有人能指出我哪里出错了以及如何正确运行LIKE查询,请。

<?php
/**
 * Created by PhpStorm.
 * User: HaiderHassan
 * Date: 9/3/14
 * Time: 9:52 PM
 */
header('Access-Control-Allow-Origin: *');
try {
    $conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
if($_POST['searchFilter']){
    $searchFilter = "%".$_POST['searchFilter']."%";
    echo $searchFilter;
    $stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    print_r(json_encode($results));
}

我在表格中有两列(roomnamesroomIDroomName 我想获得与发布值匹配的数据结果。

3 个答案:

答案 0 :(得分:5)

您有多个问题:

a)易受SQL注入攻击的影响 b)LIKE之后缺少空格,这意味着你正在生产

... LIKE%foo%

c)搜索参数周围缺少引号,因此即使您确实修复了b),您仍然会遇到问题。它应该是

... LIKE '$searchParameter'
         ^----------------^--- note the quotes

答案 1 :(得分:2)

在这一行:

    $stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
  1. LIKE
  2. 背后必须有空格
  3. 您需要将字符串括在apostroph之间以使其成为实际的SQL字符串
  4. 肯定 使用parametrized queries,因为现在这是一个巨大的SQL注入漏洞(如果有人搜索';delete from roomnames; select '怎么办?)

答案 2 :(得分:2)

应准备声明

if($_POST['searchFilter']){
    $searchFilter = $_POST['searchFilter'];
    echo $searchFilter; 
    try {
        $conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT roomName FROM roomnames WHERE roomName LIKE ?");
        $stmt->execute(array('%'.$searchFilter.'%')); 
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        //print_r($results);
        echo json_encode($result);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
}