SEARCH PHP MYSQL QUERY - php

I am trying to make a search program. I have three tables: postivewords, negativewords and recommendationwords. These tables consist only of word_id then the word. How I do it in a query? This is what I have so far. Please correct me if I am wrong.
if(isset($_POST['searchword']))
{
$word = $_POST['search'];
$search1= mysql_fetch_array(mysql_query("SELECT * FROM positivethesaurus where word like '%$word%'"));
$search2= mysql_fetch_array(mysql_query("SELECT * FROM negativethesaurus where word like '%$word%'"));
$search3= mysql_fetch_array(mysql_query("SELECT * FROM recommendationthesaurus where word like '%$word%'"));
}

select * from negativethesaurus, positivethesaurus,recomendationthesaurus where negativethesaurus.word like '%"word%' or positivethesaurus.word like '%word%' or recomendationthesaurus.word like '%word%';
This may be not the fastest way (you would use indexes and freetext) but it will be down on only one query.
Oh yes, that been said this query is vulnerable to sql injection attacks.

also do mysql_escape_string to avoid sql injection
$word = $_POST['search'];
$word = mysql_escape_string($word);

$query = SELECT positivethesaurus .*,negativethesaurus.*,recommendationthesaurus.* FROM positivethesaurus,negativethesaurus,recommendationthesaurus where positivethesaurus.word like '%$word%' OR negativethesaurus.word like '%$word%' OR recommendationthesaurus.word like '%$word%'";
UPDATES
if you want to check if results not found then do it like this
<?php
$query = mysql_query("Your Query Here");
$rowCount = mysql_num_rows($query);
if($rowCount>0) {
// DO YOur STUFF IF RESULTS FOUND
} else {
echo "No Results Found";
}
?>
Please not that mysql_* function should not be used
Hope this works. Not Tested though. Let me know if you find any problem

1) Select the respected column instead of select * from
2) avoid sql injection

Related

LIKE function SQL

I've been using the function LIKE in this statement however its not doing what I expected for it to do, Basically a user on my site has a subject which usually looks like this hello welcome to my #room hows it going #fun and what im using is the LIKE function to select all users with the subject containing #fun my statement looks like this;
$search = 'fun';
$sql = "SELECT * FROM `usr_users` WHERE `subject` LIKE '%$search%'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['username'];
}
however when the query runs it only selects the users which have fun at the begining of their subject or not at all. is there a different function I can use to select words from within in the subject not just the first word.
You also need a % at the beginning of the string to search.
$sql = "SELECT * FROM `usr_users` WHERE `subject` LIKE '%$search%'";
--- UPDATE ---
It may be failing you because you may need to escape the data. check for errors mysql_error() against your query. It might be throwing you something about it. mysql_real_escape_string(). That # could be the culprit if it's part of your actual query. Or use htmlspecialchars() or something like that to echo out the query.

Search item using LIKE when they're saved with HTMLENTITIES

I'm using latin special characters on my database. For exemple:
The word "FLÁVIO" is saved like
flávio
I'm trying to use LIKE to search this item.. for example.. Users search for "Flávio" and I would like to return "flávio".
I tried to do something like this:
$search = $_POST['search'];
$search = htmlentities($search);
$sql = "SELECT * FROM table WHERE column LIKE '%$search%';
The conversion is done, but when I put this $search on the SQL Query it doesn't match.
How can I fix? Thanks.
Just an idea, but have you tried using REGEXP?
$sql = "SELECT * FROM table WHERE column REGEXP '$search'";
I wonder if that will make a difference.

mysql like statement is not working as expected

I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.

Trigger database search result with multiple keywords

I have a PHP search script that searches a MySQL database to answer questions. Currently my database is set out like this...
idquestion = what is the timeanswer = The time is 12:00
This data is then sent to my PHP code:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM questions WHERE `question` LIKE '%{$query}%' LIMIT 1";
$searchResult=mysql_query($searchSQL);
while($row=mysql_fetch_assoc($searchResult)){
$results="{$row['answer']}";
}
echo $results;
}
?>
Currently, the users query must contain exactly the same text as the question field. My question is; how can I make this work so it triggers a certain for several keywords?
I hope you can understand my question
I think full test search index can help
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html SOUNDEX function can be useful in this context too.
You can split query to keywords and generate dynamic SQL but it is inefficient (performance issues SQL injection attacks ) see http://php.net/manual/en/function.split.php
Alternative is to add table QUESTION_KEYWORD(QUESTION_ID,KEYWORD), split question and search this table to find best QUESTION_ID, but full text search index is more efficient. In fact full text search index uses similar data structure to optimize test search.
For an easy quick-fix based on your comment you could do something as simple as this:
// Assuming query string is ?q=make,sponge,cake
$searchSQL="SELECT * FROM questions WHERE ";
$count = 0;
foreach (explode(',', $_GET['q']) as $query) {
$searchSQL .= "`question` LIKE '%" .mysql_real_escape_string(trim($query)) . "%' ";
if ($count++ > 0) {
$searchSQL .= ' OR ';
}
}
$searchSQL .= ' LIMIT 1';
$searchResult = mysql_query($searchSQL);

Securing PHP MySQL code

I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.
Here is my code:
<?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
if(strlen($query)>0){
$suggestions=$database->query(
"SELECT * FROM search WHERE name LIKE '%" . $query .
"%' ORDER BY value DESC LIMIT 5");
if($suggestions){
while($result=$suggestions->fetch_object()){
echo '<a>'.$result->name.'</a>';
}
}
}
}
?>
Actually there aren't, considering you are escaping the only external value in the SQL
Anyway I suggest you to use PDO::prepare for queries. Go here for further infos
http://it.php.net/manual/en/pdo.prepare.php
Example:
$sth = $dbh->prepare('SELECT * FROM article WHERE id = ?');
$sth->execute(array(1));
$red = $sth->fetchAll();
Some tips from me:
use PDO,
don't concatenate query parameters, use prepared statements in PDO,
don't put "*" in SELECT statement, get only the columns you'll need,
use fetchAll() in PDO, don't fetch records in while() loop.

Categories