LIKE function SQL - php

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.

Related

SQL LIKE literally not showing any results (at all)

I tried to make a search system which uses the LIKE operator to search results based on what the user typed. I'm using it with strings. The problem is that it doesn't show any result.
I hope this also helps people with the same confusion as me...
Code:
"SELECT * FROM table WHERE name LIKE ' . $input . ';";
input is a PHP variable from what the user typed.
EDIT: Don't worry about SQL injection, it's all offline.
for the proper use of like you should use wildchar eg :
SELECT * FROM table WHERE name LIKE concat('%', ? ,'%') ;
and you should not use var inside SQL code .. you are at risk for sqlinjectiomn
for avoid this you should take a look at you db driver for prepared statement and binding param
eg for PDO
$st = $conn->prepare("SELECT * FROM table WHERE name LIKE concat('%', ? ,'%')");
$st->bindParam(1, $input, PDO::PARAM_STR, 255);
$st->execute();
Try This
$string = "input";
$sql = "select * from table where name like '%$string%'"
Create a variable and store value what you want to search
$where = "AND name like '%$string%'";
and put it after table name
$sql = "select * from table_name $where";

MySQL select query comma separated numbers filter result

My table look like this:
Table screenshot
Here I'm getting the result by query:
$subject_ids = implode(',', $_POST['subject_ids'])
SELECT * FROM table WHERE focusarea LIKE '%$subject_ids%' ;
The result is perfect, but there is nothing to display when I select more than one subject ids, like if selecting only one then it shows,
but when to select 1, 2, and 4, but there is nothing with this LIKE query...
How can I fix this?
Use implode like,
PHP
$subject_id_aray = explode(",",$_POST['subject_ids']);
$in_array_string = array();
foreach($subject_id_aray as $values){
$in_array_string[] = "'".$values."'";
}
MySql
$sql = "SELECT * FROM table WHERE focusarea in (".implode(",",$in_array_string).") ;";
LIKE clause will not work in your case because using LIKE '%1,2,3%' in query will not get anything, as you as using Ids you should use IN instead of LIKE. LIKE will be used separately for each id if it is string.
As you are getting $_POST['subject_ids'] as an array, query will be like
$subject_str = implode(',', $_POST['subject_ids']);
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
If your column focusarea is not integer then
$subject_str = "'".implode("','", $_POST['subject_ids'])."'";
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
Maybe you have bug in POST.
Try to echo, $subject_ids befor inject to SQL.
You focus are is simple string of numbers, connected by ,, but what you are sending by POST maybe is not correct.
Other problem, this don't look like you full code.
Provide you file, if this don't resolve problem.

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.

SEARCH PHP MYSQL QUERY

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

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.

Categories