Best search match - php

I am trying to implement the most relevant search result for a website.
Below is how I want it to look like:
If someone types in "Beauty" it should first search if any account username has the handle "#beauty" and display that one first, then the rest of the accounts that match the criteria below:
Matching keyword
Keyword in handle or account name
Keyword in account's bio
The code I am currently using:
$searchset = mysqli_real_escape_string($conn, rtrim($_GET['search']));
$sql = "SELECT * FROM accounts WHERE username LIKE '%".$searchset."%' OR keywords LIKE '%".$searchset."%' OR bio LIKE '%".$searchset."%')";
I have been reading on methods using weighted search or mysql MATCH(), but I couldn't figure out the best code to achieve my required results.

A simple ORDER BY should do the job:
$sql = "SELECT * FROM accounts WHERE username LIKE '%".$searchset."%' OR keywords LIKE '%".$searchset."%' OR bio LIKE '%".$searchset."%') ORDER BY '$searchset' != username";
You should look into prepared statements, and I recommend using PDO instead of mysqli. The syntax is much more modern and there are many shortcuts and convenience methods available.

Related

Putting another query inside the where clause mysql and php

What is the simplest way of putting another mysql query inside a where clause in php.
For example I have tried:
$sql = "SELECT app, description FROM all-apps WHERE app!='(SELECT user, app FROM users-apps WHERE user="$user_name")'";
I need to bring up all the apps entries in the database. and then check if the user has the same app name in his list. if so it will not show up.
Basically there are 2 databases one has all apps and the other one has apps which the users have used and I need the query to find all the apps the user has not used.
Please comment bellow if this question is up to standard. Please have an opinion so I can fix on my mistakes in the future.
A few changes needed
"SELECT app, description FROM all-apps WHERE app NOT IN (SELECT app FROM users-apps WHERE user='{$user_name}')";
Note that this and your original query may leave you vulnerable to sql injection. Please use PDO prepared statements.
Thanks, with all of your help I was able to get this query to work:
$sql = "SELECT * FROM all_apps WHERE app NOT IN (SELECT app FROM users_apps WHERE user='{$user_name}') ";
This works by first selecting one table. Then choosing what column you want the WHERE to be. Then put IN if you want it to be in or NOT IN. Then in brackets your second query. Make sure to have it only select the one column. The IN clause also works if there are multiple results.

select from a select statement in php & mySQL

I am trying to add filters to a DB search. I have a search that takes some text and tries to find items with that text in the title. I also have a price range filter. That code is below and works just fine
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' AND price > '". $price1 ."' AND price < '".$price2."' Limit 70";
Now I am trying to more and more filters. Is there a select from the above code's output? I don't want to just keep making a longer SELECT statement with tons of if statements. I'd prefer to take the output of the previous select and refine that with another select. Is this possible?
EDIT 1 Context:
Users are the ones entering the information. This is for searching the items on my site.
There's no other useful way than adding lots of different conditions to your WHERE cause, if you use plain SQL. It is possible to use several nasted SELECT statements in your query, but this makes your code neither any more readable nor faster.
A more elegant solution is the usage of query objects or another form of object-oriented query abstraction (e.g. ZendDB).
You can use some of the mysql string functions like INSTR(), MATCH which will make your life a little easy and also help the readability of the code.
You can also use REGEXP and NOT REGEXP for pattern matching . The list of string functions are here.

php & mysql search query escape

I have a movie database website and I'm having a small issue with the search.
Lets say that the movie name saved in the database is
Going Clear: Scientology and the Prison of Belief
As you can see there a : in the title.
When my users search for Going Clear Scientology and the Prison of Belief they get no results, same if the movie title has ', here is my search query:
SELECT * FROM movie WHERE title LIKE '%$search%'
How can I fix that?
Keep two things in mind when trying to insert into the database using php.
First, when you are inserting into the database your data, say for example the movie name here "Going Clear: Scientology and the Prison of Belief", trim off the extra strings like : . This well help you later on.
Second, similar to the first one, when you are taking an input from the user sanitize it. There might be strings like ',$,\,? etc which are not relevant. After you have done that you can go for a query search in the DB.
I guess your code here is okay.
select * from movie where title like 'Going%';
The above query works for me when I check it in my DB. See if your search variable is initializing properly.
You need to escapes special characters in a string for use in an SQL statement. Always store these type of value into database after escaping special character and also pass your search term into query after escaping special character.
For this you have to use
mysql_real_escape_string()
Eg:
$search = "Going Clear: Scientology and the Prison of Belief";
$search = mysql_real_escape_string($search);
$query= "SELECT * FROM movie WHERE title LIKE '%$search%'";
You can read here
http://php.net/manual/en/function.mysql-real-escape-string.php

What's the best way to apply the same rule in multiple queries?

My application has a dashboard screen which has many charts showing metrics and results of user activity, sales performance, etc.
These results can be filtered by date, user and many other options. Supposing I've got one query for each chart, what's the best way to apply the same filtering rule in these multiple queries? Whats the best way to replicate the same "where" clause (the same filtering rule) accross many queries?
As example,
SELECT * FROM users WHERE date = '2014-10-03';
SELECT * FROM products WHERE date = '2014-10-03';
Both queries have same rules.
Some suggested to set a variable with this rule and concatenate it to other queries. Something like:
$where = "WHERE date = '2014-10-03'";
$query = "SELECT * FROM users ". $where;
...
$query = "SELECT * FROM products ". $where;
...
But I can't see this as a good pratice.
If it is similar to issue I had in past I guess you need these restricted by many often repetitive WHERE conditions. User, department permission, time, etc.
What worked in my case was making these into string variables and reusing them across queries that produce charts and graphs. Of course, do not insert user data into your dynamic queries. Hope it helps.
Would it not be a better idea to only keep the value dynamic in case tables do not share the same column name for date.
$date = '2014-10-03';
$query = "SELECT * FROM users WHERE `date_added` = $date";
$query = "SELECT * FROM products WHERE `date_purchased` = $date";
Note: use appropriate validation and security checks for using user input data in sql.
I think you should look into using Prepared Statements. Similar to bind variables in Oracle.
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters
Good explanation here: http://docs.php.net/pdo.prepared-statements
Prevents SQL injection attacks as well

select defined string value with mysql query of a table

i have a table called username which has for example John Doe and i want to get this value in a php action for $username! I use this
mysql_query("SELECT * FROM photos WHERE username = '$username'");
it works fine. Im using this for a searchfield to return different Users and their profile.
The question is, how can i search with eg only the first name John and he gives me John Doe back.
I dont want to create a first and last name!
Thanks Ted
SELECT * FROM photos WHERE username LIKE '%$username%';
With a word on security: If $username is the value of a search field in your site, you should escape the given search pattern correctly, not to get your database injected. This is simply done by the following code:
$escaped_username = mysql_real_escape_string($_REQUEST['username']);
mysql_query("SELECT * FROM photos WHERE username LIKE '%$escaped_username%'");
This will perform a secure search in your table, with the possibility of using just first or last name.
Legend: $_REQUEST['username'] is the value of your search form.
You can use LIKE for pattern matching,
SELECT * FROM photos WHERE username LIKE CONCAT('%','$username', '%')
but this will perform slow in large database because it will not use index causing to perform FULL TABLE SCAN.
$query = "SELECT * FROM photos WHERE username LIKE CONCAT('%',$username, '%')"
mysql_query($query);
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
You can use LIKE MySQL clause in the query
SELECT * FROM photos WHERE username LIKE '$username%'
You can use CONCAT Function to get Full name
SELECT CONCAT(First_name, ' ', Lastnale,)
FROM photos
WHERE username LIKE '$username%'

Categories