问题描述 投票:0回答:3
也是,如果您不希望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']."%' ");
php
3个回答
0
投票

如果我理解您的问题,我不会解决,但我认为此查询可能会对您有所帮助。

SELECT * FROM search_locations WHERE 'bs3 5qu' LIKE CONCAT(location_postcode,'%')
它用作“对面的通配符”,将通配符与位置_postCode相连而不是用户的输入。

其他选项,如果我们假设邮政编码长2个字符,则是使用MySQL左功能来获得一个子字符串,如下所示:

SELECT * FROM search_locations WHERE location_postcode LIKE LEFT('bs3 5qu', 2)
希望它有帮助!

0
投票

大家。目标是拥有一个搜索框,用户可以搜索邮政编码或位置。
数据库被列出了:

location_id location_name location_postcode 1 bristol bs 2 glasgow g

有些邮政编码仅从一个字母开始,有些是从上面的两个字母开始的,例如上面的数据库示例。现在,下面的代码我将$ location_search变量更改为第一个字母,如果它是一个带有一个字母的邮政编码,则将其更改为第一个字母,如果它是带有两个字母的邮政编码,则将其更改为两个字母。现在,如果它的位置(例如布里斯托尔)。它会忽略邮政编码并将整个单词分配给变量$location_search.

现在我刚刚完成了此代码。可能会更好,但奏效。分配给变量后,您可以使用它来运行mysql查询。

<?php //Assign location ID $location_word = mysql_real_escape_string($_POST["location_input"]) if(!empty($location_word)){ //Remove spaces $location_word = str_replace(" ", "", $location_word); //Work out if it's a postcode or a location. $location_3rd_character = substr($location_word, 2, 1); //Get third character if(!ctype_alpha($location_3rd_character)){ //Check if it's a number or not $location_type = "postcode"; } else { $location_type = "city"; } if($location_type == "postcode"){ //Definding the postcode search, strip down to first or second letter. $location_2nd_character = substr($location_word, 1, 1); if(!ctype_alpha($location_2nd_character)){ //Trim postcode down to one letter, if only one letter in postcode. $location_search = substr($location_word, 0, 1); } else { //Trim postcode down to two letters, if only two letter in postcode. $location_search = substr($location_word, 0, 2); } } else { $location_search = $location_word; } ?>


0
投票
这个问题更多地在您的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);


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.