-1

我正在尝试使用 php 的 mysqli 扩展为 LIKE 查询做一个准备好的语句。但无论我尝试什么,我总是会得到这个错误:

Fatal error: Problem preparing query (SELECT f.*,r.slug FROM `foods` AS f INNER JOIN `resturants` AS r ON f.`rest_id` = r.`rest_id` WHERE f.`name` LIKE CONCAT('%',"f", '%')) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''%',"f", '%')' at line 4 in /path/to/class.mysqli.php on line 462

我尝试了以下查询无济于事:(
$s将是我要搜索的字符串。)

SELECT f.*,r.slug FROM `foods` AS f
INNER JOIN `resturants` AS r
ON f.`rest_id` = r.`rest_id`
WHERE f.`name` LIKE '%?%'

SELECT f.*,r.slug FROM `foods` AS f
INNER JOIN `resturants` AS r
ON f.`rest_id` = r.`rest_id`
WHERE f.`name` LIKE CONCAT('%', ?, '%')


SELECT f.*,r.slug FROM `foods` AS f
INNER JOIN `resturants` AS r
ON f.`rest_id` = r.`rest_id`
WHERE f.`name` LIKE CONCAT('%', {$s}, '%')


SELECT f.*,r.slug FROM `foods` AS f
INNER JOIN `resturants` AS r
ON f.`rest_id` = r.`rest_id`
WHERE f.`name` LIKE '%{$s}%'

甚至:

sprintf("SELECT f.*,r.slug FROM `foods` AS f
INNER JOIN `resturants` AS r
ON f.`rest_id` = r.`rest_id`
WHERE f.`name` LIKE '%%%s%%'", $s)

请帮助我,我越来越沮丧。

4

2 回答 2

4

我会将 LIKE 之后的表达式移动到变量:

$param = '%somestring%';

$sql = "SELECT f.*,r.slug FROM `foods` AS f
INNER JOIN `resturants` AS r
ON f.`rest_id` = r.`rest_id`
WHERE f.`name` LIKE ?"

更新:

也许这会有所帮助

-- test.sql
CREATE TABLE supportContacts (
     id int auto_increment primary key, 
     type varchar(20), 
     details varchar(30)
);

INSERT INTO supportContacts
(type, details)
VALUES
('Email', 'admin@sqlfiddle.com'),
('Twitter', '@sqlfiddle');

<?php
// test.php
$mysqli = new mysqli("localhost", "root", "root", "test");
$sql = 'SELECT type FROM supportContacts WHERE type LIKE ?'; // here is only ?, no %

$stmt = $mysqli->prepare($sql);
$type = 'E%'; // and here you can put % sign
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
var_dump($result);
于 2013-03-05T17:32:12.840 回答
0

%的 's 也需要用引号括起来。

于 2013-03-05T17:09:36.637 回答