我的sql语句搜索我的数据库时遇到了一些问题。我需要这个来专门搜索输入的短语,例如天空盒只会返回天空盒而不是天空盒子绿色。我得到的错误和代码可以在下面看到:
代码:
$term = "searchTerm";
SELECT * FROM `0530-0605` WHERE SearchTerm = [[:<:]]:searchTerm[[:>:]] UNION ALL SELECT * FROM `0606-0612` WHERE SearchTerm = [[:<:]]:searchTerm[[:>:]] UNION ALL SELECT * FROM `0613-0619` WHERE SearchTerm = [[:<:]]:searchTerm[[:>:]] UNION ALL SELECT * FROM `0620-0626` WHERE SearchTerm = [[:<:]]:searchTerm[[:>:]] UNION ALL SELECT * FROM `0627-0703` WHERE SearchTerm = [[:<:]]:searchTerm[[:>:]]
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchTerm", $term);
$stmt->execute();
foreach($stmt as $row) {
$file = $row['SearchTerm'];
}
错误:
致命错误:未捕获的异常&#39; PDOException&#39;与消息 &#39; SQLSTATE [42000]:语法错误或访问冲突:1064您有 SQL语法错误;查看与您的手册相对应的手册 MySQL服务器版本为正确的语法使用附近 &#39; [[:&lt;:]]&#39; sky-box-not-working&#39; [[:&gt;:]] UNION ALL SELECT * FROM
0606-0612
在哪里&#39;
不确定如何解决这个问题,因为研究表明[[:&lt ;:]]一词[[:&gt;:]]是达到我想要的方式但显然不起作用< / p>
答案 0 :(得分:0)
我不确定是什么研究让你使用它:[[:<:]]:searchTerm[[:>:]]
,但它似乎不是有效的MySQL语法。
使用PDO,您只需在sql查询中添加占位符,例如使用:searchTerm
然后使用bindParam()
绑定参数,请参阅下面的完整示例。
请参阅此处的手册:http://php.net/manual/en/pdostatement.bindparam.php
根据您的代码:
$term = "searchTerm";
$sql = "
SELECT * FROM `0530-0605` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0606-0612` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0613-0619` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0620-0626` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0627-0703` WHERE SearchTerm = :searchTerm";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchTerm", $term);
$stmt->execute();
foreach($stmt as $row) {
echo '<pre>'. print_r($row, true).'</pre>';
}
答案 1 :(得分:0)
根据OP提供的新代码更新答案:
$term = "searchTerm";
$query = "SELECT * FROM `0530-0605` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0606-0612` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0613-0619` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0620-0626` WHERE SearchTerm = :searchTerm
UNION ALL
SELECT * FROM `0627-0703` WHERE SearchTerm = :searchTerm";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchTerm", $term);
$stmt->execute();
foreach($stmt as $row) {
$file = $row['SearchTerm'];
}
请记住,将PDO与占位符一起使用时,无需转义值(如mysqli所示):PDO会为您处理。