mysql_query("
SELECT
location_postcode,
CASE SUBSTRING('".$_POST['user_postal_search']."', 1, 2)
WHEN 'bs' THEN 'Bristol'
WHEN 'ba' THEN 'Bath'
ELSE 'Unknown City'
END CASE as City
FROM
search_locations
WHERE
location_postcode LIKE '".$_POST['user_postal_search']."%'
");
也是,如果您不希望SQL Server处理子字符串,那么只需让PHP做到这一点:
mysql_query("
SELECT
location_postcode,
CASE '".substr($_POST['user_postal_search'], 0, 2)."'
WHEN 'bs' THEN 'Bristol'
WHEN 'ba' THEN 'Bath'
ELSE 'Unknown City'
END CASE as City
FROM
search_locations
WHERE
location_postcode LIKE '".$_POST['user_postal_search']."%'
");
它用作“对面的通配符”,将通配符与位置_postCode相连而不是用户的输入。 其他选项,如果我们假设邮政编码长2个字符,则是使用MySQL左功能来获得一个子字符串,如下所示:
SELECT * FROM search_locations
WHERE location_postcode LIKE LEFT('bs3 5qu', 2)
希望它有帮助!
这个问题更多地在您的Web服务器代码上,而不是DB。如果您使用PHP检索用户的输入,则是您如何做的示例:
<?php
// Retrieve the user's input.
$postCode = $_POST["postCode"];
// Sanitize, making sure it may only contain alpha-numerical characters for security and make lower-case.
$postCode = strtolower(preg_replace("/[^a-z]/i", "", $postCode));
// Retrieve the first two characters from the user's input.
$postCode = substr($postCode, 0, 2);
// Now query the database like you did before.
$location_query = mysql_query("SELECT * FROM search_locations WHERE location_postcode LIKE '" . $postCode . "%'",$db_connect);