duancuo1234 2014-09-06 15:09
浏览 60
已采纳

PDO为单个字符串运行多个表列的LIKE查询

I want to use like on two columns in my table now.

tablename = roomnames

table columns = roomID, roomName, roomNo

i have an input field which sends a string value on which the query should execute.

Here below is the PHP PDO code

<?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'];
    $stmt = $conn->prepare("SELECT roomName, roomNo FROM roomnames WHERE roomName LIKE ? OR roomNo LIKE ?");
    $stmt->execute(array('%'.$searchFilter.'%'));
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    print_r(json_encode($results));
}

the query i tried is wrong and not working here is what i tried now.

$stmt = $conn->prepare("SELECT roomName, roomNo FROM roomnames WHERE roomName LIKE ? OR roomNo LIKE ?");
$stmt->execute(array('%'.$searchFilter.'%'));

i want if i search room No or roomName, it will show me result if that room number or room name is present in the table of database.

Sorry for my bad English. I hope i have explained. i want to search in multiple columns for a table against a input string, Input string can be a no or name. Number is for roomNo and name for room name.

  • 写回答

2条回答 默认 最新

  • dtn36013 2014-09-06 15:13
    关注

    You've got to have a value for every parameter, so double your searchfilter in the array of the values for the parameters:

    $stmt = $conn->prepare("SELECT roomName, roomNo FROM roomnames WHERE roomName LIKE ? OR roomNo LIKE ?");
    $stmt->execute(array('%'.$searchFilter.'%','%'.$searchFilter.'%' ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?