不能用多个选择LIKE的PDO

时间:2018-03-08 15:59:45

标签: php pdo

遇到以下代码问题。它没有给出错误,也没有输出任何内容。问题在于multipleReg部分。如果我删除bindValue multiplereg并将select语句中的:multiplereg替换为$multipleReg则可行。我有一种感觉,因为它不是一个阵列,但我已经尝试将它作为一个没有工作的阵列来执行。任何帮助将不胜感激。

<?php
header('Content-Type: application/json; Charset=UTF-8');
require "includes/config.php";

$offset = $_GET["offset"];
$region = trim($_GET["region"]);
$regionExp = explode(",", $region);
$tag = $_GET["tag"];

$data = array();

foreach ($regionExp as $singleReg)
    $queryKeyword[] = "'%$singleReg%'";

$multipleReg = implode(' OR region LIKE ', $queryKeyword);

try {
    $sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag) AND 
(region LIKE :multipleReg) ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";

$stmt = $db->prepare($sql);
$stmt->bindValue(':tag', $tag);
$stmt->bindValue(':multipleReg', $multipleReg);
$stmt->bindValue(':offsetNr', (int) $offset, PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $data[] = $row;
}
echo json_encode($data);
$stmt->closeCursor();
exit();
} catch(PDOException $e) {
    echo $e->getMessage();
}
?>

1 个答案:

答案 0 :(得分:1)

您可以创建一个数组来准备SQL字符串,另一个数组来存储占位符:

$qstr = [];
foreach ($regionExp as $k => $singleReg) {
    $queryKeyword[':lk'.$k] = "%$singleReg%";
    $qstr[] = 'region LIKE :lk'.$k ;
}

然后你的SQL查询(不要忘记检查$qstr是否为空):

$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag) 
   AND (".implode(' OR ', $qstr).") 
   ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";

并绑定:

// Instead of : $stmt->bindValue(':multipleReg', $multipleReg);
foreach ($queryKeyword as $k => $v) $stmt->bindValue($k, $v);

编辑完整代码:

$offset = $_GET["offset"];
$region = trim($_GET["region"]);
$regionExp = explode(",", $region);
$tag = $_GET["tag"];

// This part has changed :
$qstr = [];
foreach ($regionExp as $k => $singleReg) {
    $queryKeyword[':lk'.$k] = "%$singleReg%";
    $qstr[] = 'region LIKE :lk'.$k ;
}

try {

    // The SQL string changed
    $sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
            AND (".implode(' OR ', $qstr).")
            ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";

    // Debug (see below)
    // echo $sql."\n" ;
    // print_r($queryKeyword);

    $stmt = $db->prepare($sql);
    $stmt->bindValue(':tag', $tag);

    // The line below replaced
    foreach ($queryKeyword as $k => $v) $stmt->bindValue($k, $v);

    $stmt->bindValue(':offsetNr', (int) $offset, PDO::PARAM_INT);
    $stmt->execute();

    $data = array();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $row;
    }
    echo json_encode($data);
    $stmt->closeCursor();
    exit();
} catch(PDOException $e) {
    echo $e->getMessage();
}

SQL和转储将如下所示:

SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
   AND (region LIKE :lk0 OR region LIKE :lk1)
   ORDER BY id DESC LIMIT 10 OFFSET :offsetNr

Array
(
    [:lk0] => %test%
    [:lk1] => %test2%
)