I’m putting together a simple search engine for a small site. Users will be able to search for their friends by their email address or name. I was hoping to use FULLTEXT search, but I’m using InnoDB tables, so that takes me back to LIKE %keyword%.
My problem is that users have their first name and last name stored in two separate columns. How can I go about searching for “David Rule” is a situation like that?
Here’s what I have at the moment:
if(filter_var($query,FILTER_VALIDATE_EMAIL)) {
$STH = $this->_db->prepare("SELECT UserID
FROM UserCredTable
WHERE EmailAddress = :query;");
} else {
$STH = $this->_db->prepare("SELECT UserID
FROM UserInfoTable
WHERE FirstName LIKE :query
OR LastName LIKE :query;");
}
It sort of works, but I’m guessing relevance is pretty much non-existent 🙁
How can I sort by the most relevant results?
Update:
Does this seem like a decent solution?
if(filter_var($query,FILTER_VALIDATE_EMAIL)) {
$params["query"] = $query;
$STH = $this->_db->prepare("SELECT UserID
FROM UserCredentials
WHERE EmailAddress = :query;");
} else {
$params["query"] = "%".$query."%";
$STH = $this->_db->prepare("SELECT UserID
FROM UserDetails
WHERE CONCAT(FirstName,' ',LastName)
LIKE :query;");
}
Search is obviously a big topic and there are lots of different ways to handle things.
That said, for the most basic possible solution, you should be able to search on the concatenation of those two fields:
The
CONCAT()MySQL function takes as many strings as you’re concatenating as arguments. In the above case, we’re just added a space between FirstName and LastName.