I have a member directory in a mysql database. I want users to be able to search by first initial of first or last name. I currently have code that allows searching by initial but brings up any name that has the letter in it, regardless of whether it is the first letter or not. How do I set this to only return if the first letter of wither name matches that selected?
$sql="SELECT ID, FirstName, LastName FROM stafftest WHERE FirstName LIKE '%" . $letter . "%' OR LastName LIKE '%" . $letter ."%'";
All I’ve done is remove the first % signs. The percent sign tells the mysql like statement to match any character. So in effect, you are telling it to: ‘match any character(s) (including start and end characters) and then find the letter L, then match any character(s).’. Changing this to use just one % at the end will sort your problem out.
Additionally, it’s a good idea to use prepared statements if you can. PDO is handy for that.