mysql SELECT * FROM table WHERE column+space+column LIKE '%query%' - mysql

For a search function, I need to be able to get the mysql function to show up results by combining two columns.
To be more precise: I have a table in the database called "members" in that there is a column called "firstname" and one called "lastname" which I need to use for this. When someone types in a whole name, eg. Jane Doe, I want the query to look whether combining firstname + a space(&nbsp?) + lastname brings forth any results.
My code so far is this:
$poster = mysql_query("SELECT id FROM members WHERE (firstname'&nbsp'lastname) LIKE '%$search%'") or die(mysql_error());
$poster = mysql_fetch_object($poster);
I know that's probably wrong, it's the most recent I've tried after trying with brackets around the firstname + lastname bits, etc, etc... But yes, any help would be greatly appreciated.

Use the CONCAT function:
SELECT id FROM members
WHERE CONCAT(firstname, ' ', lastname) LIKE ?

Try CONCAT
SELECT id FROM members WHERE concat(firstname, ' ', lastname) LIKE '%$search%'

SELECT id FROM members WHERE (firstname + ' ' + lastname) LIKE '%$search%'

I believe what you are looking for is:
$name_var = 'John Doe';
// Example 1 - using concatenation
$sql = "SELECT id FROM members WHERE CONCAT(firstname, ' ', lastname) = '$name_var'";
The above statement will search for everything where the first name is John and the last name is Doe
This is rather ineficcient as it will have to evaluate the CONCAT everytime in mysql I believe
I would reccomend validating in PHP that the string is two words as you expect e.g.
$name_var = 'John Doe';
// this will split the string based on spaces
$names = explode(' ', $name_var);
$first_name = $names[0];
$last_name = $names[1];
// Example 2 - searching each field
$sql = "SELECT id FROM members WHERE firstname = '$first_name' AND lastname = '$last_name'";
The above statement will still search for everything where the first name is John and the last name is Doe
In the above statment you are actually just searching based on the exact values so it is much more efficient. If this query is going to be ran regularly, you should also add indexes to the firstname and lastname fields in your mysql table as it will greatly increase the speed!
hope this helps!
Tom

Related

Replace function in mysql not working

I have a table like this;
Lastname
MORALES
THOMPSON
SMITH
but I want to use the replace function to change all the lastname to another character like this:
I want 'MORALES' to be replace with 'TEYE'
I tried this syntax;
select lastname, REPLACE(lastname, 'M', 'TEYE')
from customers;
but this is what i'm getting;
'MORALES TEYEORALES'
Instead of
'MORALES TEYE'
please I need help.
Thanks
You told it only to replace M, not the whole name, that's what it did. If you want to replace the whole name, write:
SELECT lastname, REPLACE(lastname, 'MORALES', 'TEYE')
FROM customers
REPLACE() replaces substrings, so if there's a lastname = AMORALES, the result will be ATEYES. If you only want to replace it when it's the entire name, you can use:
SELECT lastname, IF(lastname = 'MORALES', 'TEYE', lastname)
FROM customers
not an expert in mySQL; but, it looks like you are getting what you asked for, the last name folowed by the last name where the "M" was replaced with "TEYE".
have you tried appending the string you want added?
select lastname + " TEYE" (or some variation to concatenate in mySQL syntax.
if the last name only needs to be update if it currently equals "MORALES", you can most likely add a where (row selection) clause (something like where lastName = "morales") to filter the rows being updated

search box -> I need to concat first name and last name from one table and join it to a 2nd and return item from 2nd table

So the search would be like 'Ozzie Smith'
First table has (username, fname, lname) = osmith, ozzie, smith
Second table has (username, team) = osmith, cardinals
I need to concat the first and last name columns from the first table join it by username on the second table and return the team name.
I have been trying and trying...brain melted. I need your help!
Thanks!
Since it's MySQL, you need to use CONCAT, not the + sign. I also added a LOWER() function to avoid capital letter mismatch problem :
select team
from table1
join table2 on table2.username = table1.username
where lower(concat(fname,' ',lname)) like lower('%Ozzie Smith%')
You're probably doing something like
WHERE fname LIKE '%Ozzie Smith%'
which will not work. fname will contain only Ozzie, and will never match against Ozzie Smith. It would also not match if the user enters Smith, Ozzie, or any other dual-name variant. You'll have to preprocess the search terms and do something like
WHERE (fname LIKE '%Ozzie%') or (fname LIKE '%Smith%')
OR (lname LIKE '%ozzie%') or (lname LIKE %Smith%')
This will get VERY painful as the number of search terms and fields being search goes up. You'd be better off using a FULLTEXT index, where it'll be a simple matter of
WHERE MATCH(fname, lname) AGAINST ('Ozzie Smith')
Why doesn't this work?
select
lname + ', ' + fname as playerName
, team as teamName
from table1
join table2 on table2.username = table1.username
Update:
where (fname + ' ' + lname) like '%Ozzie Smith%'

MYSQL: Dynamic columns in mysql --> first, last name to full name:

I was wondering if you have two columns for lets say
first name.
last name.
what you store in the database.
Can you create a 'dynamic' column 'fullname' in the database that automatically creates the name out of the first and last name?
firstname |lastname |fullname (this goes automatically)
-----------------------------------------
foo |bar |foo bar
If you just want to select the full name, you can do just that:
select concat(firstname, ' ', lastname) as fullname from users
If you actually want a column (i.e. be able to perform updates against it), then it's not possible, AFAIK.
You can try something like this:
SELECT CONCAT(firstname, ' ', lastname) as firstlast FROM users
This one also makes sure that no empty spaces are added:
SELECT IF(ISNULL(firstname), lastname, CONCAT(firstname, ' ', lastname)) AS fullname FROM users

Override column value in WHERE clause?

I was wondering if it was possible to override column value in the Where clause of a SQL query (MySQL in my case).
To be more clear, here is an example :
Suppose a basic query is :
SELECT lastname, firstname FROM contacts WHERE lastname = "Doe";
Is it possible to force lastname and firstname to return value from an other table, just by modifying what is after the WHERE part ? Something like
SELECT lastname, firstname FROM contacts WHERE lastname = (SELECT name FROM companies);
I am currently testing a web application, and I found a SQL Injection flaw where I can change Doe to whatever I want, but I'm limited with only one query (mysql_query restriction of PHP) and addslashes (so no " and ').
possible could be
SELECT lastname, firstname FROM contacts WHERE lastname = "{0}" UNION SELECT {1} --
where {0} non existed value and {1} data from other tables
UPDATE from wiki example
$res = mysql_query("SELECT author FROM news WHERE id=" . $_REQUEST['id'] ." AND author LIKE ('a%')");
become
SELECT author FROM news WHERE id=-1 UNION SELECT password FROM admin/* AND author LIKE ('a%')
The syntax that you used in your SELECT ... WHERE clause is a standard SQL feature called a subquery.
In the context of your example there is a restriction on the subquery to return just single value. Otherwise your query is a valid SQL and you can change subquery to return multiple values (with implicit OR) using IN operator like this:
SELECT lastname, firstname FROM contacts
WHERE lastname IN (
SELECT name FROM companies
);
You can dig deeper into this subject to uncover correlated subquery.

Database - the best way, how to search names

I am solving in these days following situation:
In my DB table I have columns for name and surname.
On my page I have input for searching people, and I am struggling with a problem, how to search the name in database that is stored in two columns and I have the name as string ("Joe Green").
For example, in database I have followings:
Joe New
Joe Blue
Joe Green
Joe Francois Green
What could be the best way, how this problem to solve? I am currently working with MySQL database and Rails 3.
EDIT: Thank you guys for you replies, but I don't know, how to make the query in Rails 3 notation, is it possible to use "concat"?
if your database table engine is myISAM then use FULLTEXT search
first create FULLTEXT index by
CREATE FULLTEXT INDEX fx_name ON pages (name, surname)
then use below query to retrieve required data
SELECT *
FROM table
WHERE MATCH(name,surname) AGAINST ('keyword' IN BOOLEAN MODE)
update
alternative:use CONCAT
first create index
CREATE INDEX users_firstandlast ON users(name, surname);
option1: repeat the CONCAT in your WHERE clause (because AS doesn't create a name you can use in the WHERE clause):
SELECT CONCAT(name, ' ', surname) as fullname
FROM users
WHERE CONCAT(name, ' ', surname) LIKE '%joe green%';
option 2:
SELECT CONCAT(name, ' ', surname) as fullname
FROM users
WHERE name LIKE '%joegreen%' or surname LIKE '%joegreen%';
More information
A lot of this would be significantly simpler if you had given some indication of what language is being used at the interface between the input and the database (since Rails is usually associated with Ruby I'll assume you mean that), however....
SELECT *
FROM yourtable
WHERE CONCAT(name, ' ', surname)
LIKE CONCAT('%',REPLACE(?,' ', '%'),'%')
ORDER BY LEVENSTEIN(CONCAT(name, ' ', surname), ?)
(where '?' is replaced by your search string, and the levenstein function is described here)
Performance will be poor - a better solution would be to split the string Ruby and attempt matches of varying combinations.
One way is:
* split user's input to words
* search each word in name and surname columns
first use the split function to split the string
namearr = name.split
namestr = ""
namearr.each do |i|
namestr = namestr + i
end
then use the values in your query
stmt = "select * from mytable where CONCAT(firstname,surename)= " + namestr
you can use the sql server full text search which i do not recommend because of the performance is very bad ,or use the lucin .net which is more powerful and her are some links :
http://incubator.apache.org/lucene.net/
http://msdn.microsoft.com/en-us/library/ms142571.aspx
mark as answered if it helps :)