简体   繁体   中英

LIKE query in PDO not working

PDO queries run fine, but when i try to use LIKE query it don't work and give error. i know i am doing something wrong, please if anyone can point out where i have gone wrong and how to run the the LIKE query properly.

<?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));
}

i have two columns in table( roomnames ) roomID and roomName i want to get the result of data which matches with the posted value.

You have multiple problems:

a) Vulnerable to SQL injection attacks
b) Lacking a space after LIKE, which means you're producing

... LIKE%foo%

c) Lack of quotes around your search parameter, so even if you did fix b), you'd still have a problem. it should be

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

In this line:

    $stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
  1. There has to be a space behind the LIKE
  2. You need to enclose the string between apostrophs to make it an actual SQL string
  3. You should definitely use parametrized queries , because right now this is a gaping SQL injection hole (what if someone searches for ';delete from roomnames; select ' ?)

The statement should be prepared

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM