mySQL - like子句中的变量

时间:2013-03-20 20:24:37

标签: mysql variables sql-like

如何在LIKE子句中使用var?

以下代码未发送正确的回复......

$query = sprintf("
SELECT
place.ID AS id,

IF(
    place.translationID IS NULL,
    place.name,
    placel10n.text
    ) AS cityname,

FROM
places AS place

 LEFT JOIN `l10n-strings` AS placel10n ON (place.translationID = placel10n.translationID AND placel10n.languageCode = 'de')

 WHERE
 place.name LIKE CONCAT('$fchar', '%');
 AND
place.`status` = '1'

");

2 个答案:

答案 0 :(得分:0)

如果$fchar包含您要搜索的字符串,则执行此操作:

$sql = "
SELECT
place.ID AS id,

IF(
    place.translationID IS NULL,
    place.name,
    placel10n.text
    ) AS cityname,

FROM
places AS place

 LEFT JOIN `l10n-strings` AS placel10n ON (place.translationID = placel10n.translationID AND placel10n.languageCode = 'de')

 WHERE
 place.name LIKE CONCAT('%s', '%');
 AND
place.`status` = '1'";

$query = sprintf($sql,$fchar);

因此,如果$fchar = 'apple',那么您的查询将尝试匹配'apple%'。

答案 1 :(得分:0)

认为你可以做到

LIKE '$fchar%';

或者准备好的陈述(但不清楚你对sprintf的用法是什么)

place.name LIKE :fchar;

$fchar = $fchar'.'%';

$something->bindParam(':fchar', $fchar, PDO::PARAM_STR);