Skip to content
Advertisement

Searching full name or first or last name in MySQL database with first and last name in separate columns

I’m working with an existing database that has first name and last name seperated in the database. I need to create a function that will take one search input and return results. say my database has a structure like….

nameFirst nameLast
Joe       Smith
Joe       Jones
Joe       Brown

How could I, using MySql, take a search input that is say ‘Joe Smith’ and just get his row? But if I put just ‘Joe’ in the search field, return them all? Will I need to explode the string with a space? thanks!

Advertisement

Answer

SELECT * 
FROM table
WHERE CONCAT( nameFirst,  ' ', nameLast ) LIKE  '%Joe%'  

Be sure to sanitize any user submitted parameters such as “Joe”

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement