I am trying to construct an sql query to search my database for users. It is supposed to help users to find other users on my website to find friends.
I did some research because I knew I did not want:
$query = "SELECT userName, userID FROM user WHERE userID = $userName ";
Because it would not be an effective search if they had to type the users exact name in to find them.
After doing some research I decided to try the like term with % symbols in front and back so it could be the name with lets say numbers before or after and it would show up.
The example I found online formatted it like this:
$query = "SELECT userName, userID FROM user WHERE userID Like '%{$userName}%' ";
but when I executed this query while implemented on m y website, I ran into problems of it returning to many results. It returned results that did not include anything within my search term.
I also tried the above search query with out the brackets since I did not understand why I needed them but I got the same results.
Any suggestions on how to make the search a little stricter using the above command query?
Or any other suggestions for how I should search my database for a user to friend?
The % sign is for wildcards. So if $userName = 'apple' your query would match apple, applepie, and crabapple but not appl.
If you want an exact match remove the %s or the LIKE altogether.
Please try this. also why are you using braces..
$query = "SELECT userName, userID FROM user WHERE username Like '%$userName%' ";
Consider the strings
Apple
iApple
Apple Product
If you type Apple
Like '%{$userName}%' "
Returns: Will return you Apple, iApple , Apple Product
Reason: The % on both side indicates it will accept any text before and after your search term
Like '{$userName}%' "
Returns: Will return you Apple and Apple Product
Reason: The % on right side indicates it will accept any text after your search term
Like '%{$userName}' "
Returns: Will return you Apple and iApple
Reason: The % on left side indicates it will accept any text before your search term
Like '{$userName}' "
Returns: Will return you Apple
Reason: No % will restrict the search to the search term
Further More
I believe your query should be
$username = mysqli_real_escape_string($userName);
$query = "SELECT userName, userID FROM user WHERE userName Like '%{$username}%'";
Related
I'm trying to use MATCH SQL command with a server side datatables script but somehow the datatables is unable to work, it does not find any results but if I copy and paste the query output to any sql client, it works fine and find the expected results (matches).
To put you in context, this is what i've done right now:
1-Create a FULLTEXT index on the database with the columns that will be used for the search:
ALTER TABLE site ADD FULLTEXT INDEX fulltext_index_site (id, title, domain);
2-Changed the logic for search strings in the server side script:
$searchValue = mysqli_real_escape_string($mysqli,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND MATCH(id, title, domain) AGAINST('".$searchValue."' IN BOOLEAN MODE)";
}
3-I've changed the query to use the MATCH command:
select id, title, domain
from site
where 1 ".$searchQuery."
4-But if I go and search something on the client side, no results are found...I've also checked the payload and the search[value] is with the value to be searched but does not return any result. Even I've put an echo and get the output:
select id, title, domain
from site
where 1 AND MATCH(id, title, domain) AGAINST('test' IN BOOLEAN MODE);
And works fine on the sql client, it returns all the rows that matches with the 'test' pattern but on datatables just say "No results found".
5-I've even tried using a LIKE OR approach but that is not properly working because the pattern must be a coincidence on every column searched.
e.g.
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (id LIKE '%".$searchValue."%' OR title LIKE '%".$searchValue."%' OR domain LIKE '%".$searchValue."%')";
}
I'm a little burned out with this and run out of ideas why does not work on the server-side script but instead works on a sql client.
Any help will be highly appreciated.
I found the issue! i got a repeated
$row = $result->fetch_assoc() before the while ($row = $result->fetch()) that was smashing the rows! thanks.
I have PHP code to do a simple MySQL database search with only two columns of data. I suspect I am probably already going the long way around when I could simply do it a different way.
I have a form that you can put in a name or an IP address and it will search for either of them in the database, and output the results. Each name can only have one IP address (the last one they used) (full unique names will only have 1 result, or multiple results if partial names match multiple accounts), but an IP address can have multiple names (people who use multiple accounts on the same IP).
What I want to do is have it so if you search for a name, it will do the regular single result (if the full unique name was typed), but then under it, do a secondary search for the IP if only the NAME was searched for in the form.
"You search for NAME has returned these results: {results}. We also
found these accounts who have used the same IP address: {results
matching the same IP from the first result of the Name search}".
Here is the code I have so far:
(Some cleanup since I am using GET)
$iplookup = strtolower($_GET['iplookup']);
$iplookup = stripslashes($iplookup);
$iplookup = strip_tags($iplookup);
$iplookup = preg_replace('/[^A-Za-z0-9\._]/','',$iplookup);
$sql = mysql_query("select
* from banlistip where name like '%$iplookup%' OR lastip like '%$iplookup%'
");
if (empty($iplookup)) {
echo '<br><b>You left the search form empty.</b>';
} else {
while ($row = mysql_fetch_array($sql)) {
echo '<br/> Name: '.$row['name'];
echo '<br/> Player IP: '.$row['lastip'];
echo '<br/><br/>';
}
}
And then right here it would get that $row['lastip'] variable and then do a search for that, which would be the equivalent of just searching an ip address in the first place.
The whole purpose of this is to eliminate a couple of steps and see all of the desired results at once. Usually, in order to do an IP search, I have to search the name, highlight + copy the ip, go back to the form, and then search the IP.
The table with two columns named "name" and "lastip" respectively have data like this:
player1 111.111.111.111
player2 222.222.222.222
player3 111.000.111.000
player4 222.000.222.000
altaccount1 111.000.111.000
altaccount2 222.222.222.222
(If you searched for Player2, you would get one result, since it is a unique name. If you searched for the IP of Player2, you would get two results [player2 + altaccount2], since there is an alternate account that uses the same IP address.)
(Please excuse this very long post. I just want to provide as much details as I can, I have tried to research this, but having a block right now. Thanks so much, and again, sorry for making you read all of this.)
SELECT * FROM banlistip
WHERE lastip = (SELECT DISTINCT lastip FROM banlistip WHERE name LIKE '%$iplookup%' OR lastip LIKE '%$iplookup%')
I think what you're trying to do needs 2 seperate SQL strings, and call whichever is required for the data provided.
So if $iplookup is clearly an IP (use regex check), then:
$sql = "SELECT * FROM banlistip WHERE lastip LIKE '%$iplookup%'";
else you will use:
$sql = "SELECT * FROM banlistip WHERE name LIKE '%$iplookup%'";
A Regex you can use to check this with preg_match(), curtousy of regular-expressions.info:
$regex = '/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/';
if (preg_match($regex, $iplookup)) {
// Call IP SQL
} else {
// Call Name SQL
}
I have a table, with not many rows, and neither many columns. I am doing a Full text search on 3 columns.
My code is
$search_input = trim($_GET['s']);
$search = mysql_real_escape_string($search_input);
$search = '+'.str_replace(' ', '* +', $search).'*';
$sql = "SELECT * FROM table WHERE
MATCH(def, pqr, xyz) AGAINST ('$search' IN BOOLEAN MODE)";
$result = mysql_query($sql);
I can correctly search for terms like abcdefgh, which are present as ... abcdefgh ....
But I am receiving empty set with search terms like abc, where in table entry is present something like abc-123, and also terms like abcdefghs. (notice this is plural of above)
Clearly I need to implement partial search, or something like that.
But how do I implement such a search? Any better way to do a entire table search on user input?
Do mention anything I am doing incorrectly.
EDIT : By adding * after each word, now I am able to also search for abcde, but above problems remains.
Do you mean you don't get results for 3 letter combinations? If so, you might be hitting the mysql index length (which is usually set to 3)
More info here - http://dev.mysql.com/doc/refman/5.1/en/fulltext-fine-tuning.html
I am trying to make a search box for an ecommerce website.
The search works as follows
When a user searches for a product, the search value is being sent to a file called searchResults.php using post method via ajax
$searchVal=$_POST['searchVal'];
And then its being searched in the database from a table named product by the following query
$searchResult = mysql_query("SELECT * FROM products WHERE name LIKE '$searchVal'")
and the results are sent back as ajax response by the following if condition
if($searchResult){
echo "result";
}
else{
echo "No products found";
}
Above all everything works fine as expected.
lets assume an user is searching for cellphones and he/she types cell phone . But we have products only for category cellphones and not for cell phone. So it results No products found even though the records for cellphones are present.
I want to make it search regardless the white space, singular or plural . How can i do that ?
The right way to implement a search engine is to maintain a separate table of words and links to the record they appear in. Then....
$qry="SELECT p.*, COUNT(*)
FROM products p
INNER JOIN srchwords s
ON p.id=s.product_id ";
$searchVals=explode(' ',$_POST['searchVal']);
foreach ($searchvals as $k=>$s) {
$searchvals[$k]="'" . mysql_real_escape_string(trim($s)) . "'";
}
$qry.="WHERE s.word IN (" . implode(",",$searchvals) . ") ORDER BY COUNT(*) DESC";
An ugly and innefficient hack would be:
$qry="SELECT p.*
FROM products p";
$join=" WHERE "
$searchVals=explode(' ',$_POST['searchVal']);
foreach ($searchvals as $k=>$s) {
$qry.=$join . " p.desc LIKE '%" . mysql_real_escape_string(trim($s)) . "%'
$join=' OR ';
}
Both methods still don't not cater for plurals (just add an additional comparison for words ending in S, removing the S). You should also clean up the string to remove multiple spaces and punctuation (/^[a-z0-9 ]/i).
Or just use one of the many, well written off-the-shelf search engine solutions (e.g. the mnogo engine or Google's site search service).
Step 1: remove leading and trailling spaces:
$searchResult = mysql_query("SELECT * FROM products WHERE name LIKE trim('$searchVal')")
Step 2: replace existent spaces by '%' (it's wildcard in LIKE syntax):
$searchResult = mysql_query("SELECT * FROM products WHERE name LIKE str_replace(trim('$searchVal'), ' ', '%'")
A first step would be to explode() the search term on spaces: $terms = explode(' ', $query) and then do a 'SELECT * FROM products WHERE name LIKE "%'.$terms[0].'%" AND name LIKE "%'.$terms[1].'%" ...'.
Of course, this doesn't really solve your plurals issue.. Also, it can be very, very slow because MySQL can't use indexes on LIKE queries starting with a wildcard.
Another course of action could be to just have an "aliases" table that would look something like this:
cellphone | cell phone
cellphone | cell phones
cellphone | cellphones
...
Then you would replace the all occurances in a search query with the one on the left before querying the database for it.
The third and best and most complicated way is to use an index table. You wouldn't want to write that yourself, but I'd bet there are some great solutions out there. Personally, I'm using Doctrine, which has this feature built in.
You can use trim() in php to strip whitespace (or other characters) from the beginning and end of a string
I am trying to have PHP search based on letters entered into a text box. I want it to match a pattern and find the relevant results from the database.
So if I typed in
"Jo Smi"
It would find results
Jo Smith, Pojo Smithson, Ojo Smith
How would one achieve this. I know how to get information from the database but not parts of various fields.
The objective is to search through users searching in fields user_firstname, user_lastname and user_email
Any ideas?
You should be able to do that directly from your query.
get the text box results and escape them then do
SELECT * FROM `database` WHERE `name` REGEXP '{INPUT TEXT HERE}';
That should work I think.
You can do simplistic searching on fields in a database using the LIKE clause:
$query = "SELECT Fields FROM Table WHERE TestField LIKE '%".$escapedTextString."%'";
Do a LIKE search against an upper-cased version of your search terms. Don't forget to mysql_real_escape_string().
$searchpattern = mysql_real_escape_string(strtoupper("Jo Smi"));
mysql_query("SELECT * FROM table WHERE UPPER(column) LIKE '%$searchpattern%';");
Hello Man previous answer is good
but you want to know this info
get the variable => $name =
$_GET['name'];
if you want to make it upper case
use strtoupper();
if you want to
make it Lower case use
strtolower();
if you want to
search you should replace = with
where like where name = $name to
where name like $name
this info
abc% => variable start with abc and finish with any thing
%abc% => variable start any thing , contain abc , finish with any thing
%abc => variable start any thing ,finish with abc