MySQL: LIKE and first character
Hello Stackoverflow again! 2 MySQL questions.
$query = " SELECT
stationname
FROM
stations
WHERE
stationname >= '". mysql_real_escape_string($_GET['letter']) ."'
ORDER BY
stationname
";
First, here's the first request. The URL contains a parameter set $_GET['letter']
containing an alphabetic character. I am trying to select all lines where it stationname
starts with $_GET['letter']
. So I found this solution on another Stackoverflow thread, but it doesn't seem to work, I am getting all my lines, not just one. edit : it looks like it checks for all characters in stationname
and not just the start letter, how can I get that?
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'". mysql_real_escape_string($_POST['search']) ."'
";
Second and last question. I want to create a search engine for my site by selecting all the rows where it stationname
contains $_POST['search']
. But when I have 2 rows, one of which is called cheese
and the other is cheese2
, and I search cheese
, only gets selected cheese
, and when I search cheese2
, only cheese2
gets selected. Is there a way to choose both cheese
and cheese2
?
source to share
I am trying to select all lines where the station name starts with $ _GET ['letter']
MySQL has a feature LEFT
which seems to be what you are looking for. So basically, we extract the first letter stationname
and compare it to your letter:
where left(stationname, 1) = '" . mysql_real_escape_string($_GET['letter']) . "'";
Is there a way to choose cheese and cheese2?
Well, the solution here is a little smelly, as you have to check if is contained cheese
in cheese2
as well as if is contained cheese2
in cheese
. Try the following:
where stationname like '%" . mysql_real_escape_string($_POST['search']) .
"%' OR '" . mysql_real_escape_string($_POST['search']) .
"' like concat('%', stationname, '%')";
source to share
The wildcard text in MySQL is%, so for the first query you probably want:
$query = " SELECT
stationname
FROM
stations
WHERE
stationname LIKE '". mysql_real_escape_string($_GET['letter']) ."%'
ORDER BY
stationname
";
And for your second request:
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'%". mysql_real_escape_string($_POST['search']) ."%'
";
source to share