MySQL: LIKE and First character
LIKE
supports wildcards. %
means any number of characters (including zero), and _
means any one character`
stationname LIKE 'cheese%'
This would match cheese
and cheese2
.
You can use the %
for the first issue too.
stationname LIKE 'a%'
This will find all words that start with 'a'
.
I'm trying to select all the rows where stationname starts with $_GET['letter']
MySQL has a LEFT
function which seems to be what you're looking for. So basically we extract the first letter of the stationname
and compare it agains your letter:
where left(stationname, 1) = '" . mysql_real_escape_string($_GET['letter']) . "'";
Is there any way to select both cheese and cheese2?
Well here the solution is a little smelly, as you should check whether cheese
is contained in cheese2
and also whether cheese2
is contained in cheese
. Try this:
where stationname like '%" . mysql_real_escape_string($_POST['search']) .
"%' OR '" . mysql_real_escape_string($_POST['search']) .
"' like concat('%', stationname, '%')";
for second.
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'". mysql_real_escape_string($_POST['search']) ."%'
";