I am trying to search the field firstname and lastname for a keyword
$q1 = strtolower($_GET["q"]);
$q=str_replace(" ","%",$q1);
$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter
firstname LIKE '%$q%' OR lastname LIKE '%$q%' ORDER BY lastname";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) { echo $results }
this is what I have so far, issue is if you use John Doe as an example once you type John it finds it, doe it finds it, but john doe ... no results
I recommend that you bind the variables. You are exposed to sql injections otherwise.
$stmt = $mysqli->prepare("select * from users where firstname like ? AND lastname like ?");
$stmt->bind_param('ss', $firstname,$lastname);
Something like
SELECT * FROM users where CONCAT(firstname, ' ', lastname) like '%$q%'
Or
SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%'
And if reversing is desirable, try this:
SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%'
or CONCAT_WS(' ', lastname, firstname) like '%$q%'
(that is, if searching for "A B" should return "A B" as well as "B A")
you have to split your query string and search for each terms
$query_terms = explode(" ", $q1);
$conditions = ''
foreach($query_terms as $term){
$conditions = $conditions.' firstname LIKE "%'.$term.'%" OR lastname LIKE "%'.$term.'%"';
}
$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter $conditions ORDER BY lastname";
Related
I try to create search system using php and sql current condition is working fine but if I want
to search for John Doe (firstname + lastname) nothing happens. I try the + between firstname and lastname but it did not work.
Condition is here:
if(isset($_POST["query"])){
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query = "
SELECT * FROM users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
";
}
You msy try something like this (using CONCAT):
$query = "SELECT * FROM users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
OR CONCAT(firstname,' ', lastname) LIKE '%".$search."%'";
I have this code pretty much like a search engine within the database for peoples names.
if (isset($_POST['submit'])){
$keyword = $_POST['stats'];
$orderby = $_POST['orderby'];
if (!empty($_POST['stats'])) {
$getStats = $db->query("SELECT * FROM `stats` WHERE
`lastname` LIKE '%$keyword%' OR `firstname` LIKE '%$keyword%' OR
`nickname` LIKE '%$keyword%' ORDER BY `$orderby`
DESC");
This then prints the results back into a table, I thought the table code wasn't necessary and too long.
The above query works for if I search just the last name or just the first name, or nickname
but if there is for example a user in the database with the name, John Smith
so
Firstname: John
Lastname: Smith
If just searched 'John' he would be printed into the table, which is good and same if I just searched 'Smith'
But if I search 'John Smith' he would not be printed into the table.
How can I change this query so that this will happen, I have tried this:
$getStats = $db->query("SELECT * FROM `stats` WHERE
`firstname`, `lastname` = '$keyword' OR `lastname` LIKE '%$keyword%' OR `firstname` LIKE '%$keyword%' OR
`nickname` LIKE '%$keyword%' ORDER BY `$orderby`
DESC");
WHERE CONCAT(firstname, ' ', lastname) LIKE %$keyword%
Also you should be binding parameters rather than directly interpolating user input into the query string, your current code is vulnerable to SQL injection.
$keyword = str_replace(" ", "%", $keyword);
You can try REGEXP:
$keyword = $db->real_escape_string($_POST['stats']); // escape data
$orderby = $db->real_escape_string($_POST['orderby']); // escape data
$keyword = implode("|", explode(" ", $keyword));
$getStats = $db->query("SELECT * FROM stats
WHERE firstname REGEXP '$keyword'
OR lastname REGEXP '$keyword'
OR nickname REGEXP '$keyword'
ORDER BY $orderby DESC");
try this
$sql = "SELECT *
FROM stats
WHERE
firstname LIKE '%$keyword%'
OR lastname LIKE '%$keyword%'
OR CONCAT_WS(' ',firstname,lastname,) LIKE '%$keyword%'
OR CONCAT_WS(' ',lastname,firstname) LIKE '%$keyword%'
OR nickname LIKE '%$keyword%'
ORDER BY $orderby DESC";
i have mysql table, users: (id, first_name, last_name, ....)
i'd like to do something like this pseudo query
SELECT * FROM users WHERE first_name.' '.last_name = 'john doe' LIMIT 10")
I Want to do this cause i have lots of trouble spliting the string (then i don't know in what order is user typing'
This is my current, not working very good
$phrase = explode(' ',$term);
$last_name = '';
if($phrase[1] != '')
$last_name= " OR last_name LIKE '%".$phrase[1]."%'";
$qstring = "SELECT usuarios.first_name,usuarios.last_name,
usuarios.id as id
FROM usuarios
WHERE first_name LIKE '%".$phrase[0]."%' OR last_name LIKE '%".$phrase[0]."%' $last_name LIMIT 5";
Any suggestion to achieve this (by concatenating at query or spliting at php) would be very apreciated
You can concatenate in a MySQL query using CONCAT:
SELECT * FROM users WHERE CONCAT(first_name,' ',last_name) = 'john doe' LIMIT 10
In your code this would become:
SELECT * FROM usuarios WHERE CONCAT(first_name,' ',last_name) LIKE '%{$phrase[0]}%' LIMIT 5
Something like this?
SELECT first_name, last_name, id
FROM usuarios
WHERE CONCAT(first_name, last_name) LIKE '%$phrase[0]%' LIMIT 5
So i have this PM system.
At the recipient field, You can type in the full name of who you want to write to.
So I want to help the user alittle, if he don't remember the name.
So if you want to write the full name "Megan Fox" and only know:
Megan
Megan F
Megan Fo
Meg Fo
M Fox
etc..
It will return "Did you mean Megan Fox?" This already works fine.
Now what I need In this is that if you write only Fox , with no firstname, i want it to echo "Did you mean Megan Fox?"
Here's where Im stuck, as it creates $lastname after the space. And i really don't want to use two fields for first and last.
How can I do that?
Here's my code:
list($firstname, $lastname) = array_map('ucfirst', explode(' ', $mot, 2));
$qur = mysql_query("
SELECT id, firstname, lastname,
(firstname = '$firstname' AND lastname = '$lastname') AS full FROM users
WHERE (firstname = '$firstname' AND lastname='$lastname')
OR (firstname LIKE '$firstname%' AND lastname LIKE '$lastname%')
ORDER BY (firstname = '$firstname' AND lastname='$lastname') DESC");
$get = mysql_fetch_array($qur);
if($get["full"] == 1){
echo $get["id"];
}else{
echo "Did you mean: ".$get["firstname"]." ".$get["lastname"]." ?";
}
This should work.
$qur = mysql_query("
SELECT id, firstname, lastname,
(firstname = '$firstname' AND lastname = '$lastname') AS full FROM users
WHERE (firstname = '$firstname' AND lastname='$lastname')
OR (firstname LIKE '$firstname%' AND lastname LIKE '$lastname%')
OR ('$lastname' = '' AND lastname LIKE '$firstname%')
ORDER BY (firstname = '$firstname' AND lastname='$lastname') DESC");
OR ('$lastname'='' AND lastname LIKE '$firstname%')
I guess it is better to match against single value instead of two. For example it is hard to guess where is first name and where is last as user can type Magan Fox or Fox Megan.
so query would look like this:
SELECT id, firstname, lastname, CONCAT (firstname, ' ', lastname) AS fullname
FROM `users`
WHERE firstname LIKE '{$string}%' OR lastname LIKE '{$string}%'
GROUP BY firstname, lastname
ORDER BY firstname ASC, lastname ASC
I have this right now:
if(isset($_POST["search"]) && !empty($_POST["search"])) {
$full_name = mysql_real_escape_string($_POST["search"]);
$sex = mysql_real_escape_string($_POST["sex"]);
list($firstname, $lastname) = array_map('ucfirst', explode(' ', $full_name));
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex = '$sex'";
$result1 = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result1);
while($get = mysql_fetch_array ($result1)){
echo $get["firstname"] . " " .$get["lastname"]."<br>";
}
}
This is my search query. Now the form is called "Search for full names". You type in, and then it splits to $firstname , $lastname.
Works great, no problems.
Although if you ONLY enter a userĀ“s LASTNAME, because maybe you dont remember the users firstname, then this code will take it as a firstname, because all before a space is firstname (list() line), and puts it in $firstname and will result nothing, as there's no firstname with that lastname.
How can i solve this? If you search by firstname it works fine, full name too, but not only lastname. Any smart solution?
If I understand correctly, this is the simplest solution:
list($firstname, $lastname) = array_map('ucfirst', explode(' ', $full_name, 2));
if (!$lastname) $lastname = $firstname;
Edit: Added a limit to the explode line.
You can build a series of conditions:
Split the input on space
For each item in the resulting array, append OR firstname='value' OR lastname='value'
So smith becomes:
SELECT * FROM table WHERE (firstname='smith' OR lastname='smith') ....
And john smith becomes:
SELECT * FROM table WHERE (firstname='john' OR lastname='john' OR firstname='smith' OR lastname='smith') ....
If that's not to your liking then you can break out the search terms so you can enter first and last name separately.
Search for both(or more) list items, since names may contain spaces and look for unique results.
$arr_name= explode(' ', $full_name);
foreach($arr_name as $name){
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '$name' OR lastname LIKE '$name') AND sex = '$sex'";
$result1 = mysql_query($query) or die(mysql_error());
...
}
if (!empty($_POST["search"])) {
$name = mysql_real_escape_string($_POST["search"]);
$sex = mysql_real_escape_string($_POST["sex"]);
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort
FROM users
WHERE (firstname = '$name'
OR lastname = '$name'
OR CONCAT(firstname, lastname) = '$name'
OR CONCAT(lastname, firstname) = '$name')
AND sex = '$sex'";
$result1 = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result1);
while ($get = mysql_fetch_array($result1)){
echo $get["firstname"] . " " . $get["lastname"] . "<br>";
}
}
I simply check whether it the search input is the first name, the last name, both first name and last name or both last name and first name.
PS: A nice side affect of this version is that it will find names like Milhouse van Houten, too. Your original version (and many of the here proposed ones) couldn't deal with this case. They would look for Milhouse and van.
PPS: You probably chose a *_ci collation for the database. Thus string comparison will be case-insensitive: You don't need to ucfirst.