MySql Search With Special Character - php

I searching records from database using MySql as -
SELECT * FROM tab WHERE col LIKE '%myvalue%';
This is working fine and showing all the records having myvalue.
Now the problem is i have some records like my'value, myva'lue, myval-ue and my-value And also want to include these records in search. Also when i search for my'value then it should show myvalue and my-value.
How to achieve this? Any Help. Is it possible to do using LIKE operator?

As you are using PHP you should do the following, if someone uses your search:
Get the search-term via $_POST
Remove all special characters from the search-term (my'value becomes myvalue)
Replace the search term with MySQL wildcards (myvalue becomes %m%y%v%a%l%u%e%)
Execute SELECT * FROM tab WHERE col LIKE '%m%y%v%a%l%u%e%'
Any of the other solutions will not match all your requirements.
SQL Fiddle: http://sqlfiddle.com/#!2/20f811/2

Use
SELECT * FROM tab WHERE col LIKE '%myvalue%' OR col LIKE '%my_value%'
The underscore _ is a single character wildcard.

How about this?
SELECT * FROM tab WHERE col LIKE 'my%' OR col LIKE '%value'
this will check col should start with my and end with value.
Demo
Edit 1
As there can be any special character and regexp don't work with MySQL, I would suggest you to do what you want to achieve in PHP by replacing special character by null and then matching the string with myvalue.
Hope this helps you.
Edit 2
I don't know php exactly, but can tell you what to do little bit.
mysql = "SELECT id, col FROM tab WHERE col LIKE '%my%' OR col LIKE '%value%'";
rs = mysql.execute();
String newString = "";
while (rs.next()) {
newString = rs.getString(2);
newString = new string after replacing special characters using regexp
if (newString.equals("myvalue")) {
// your code here..... this is place what you wanted.
}
}

Got this...
PHP Part
$term = str_replace('-','',str_replace(',', '', str_replace('\'', '', $term)));
MySql Part
SELECT *
FROM tab
WHERE ((REPLACE(REPLACE(REPLACE(col, '\'', ''), ',', ''), '-', '') LIKE "%$term%")
OR (col LIKE "%$term%"));
See this demo.

Related

Fetch mysql data with different operators

Is it possible to fetch data from a database adding a dot into it using MySQL?
e.g. If I've data inserted into a DB such as 'BA', after fetching the value can I display it as B.A?
Can I also change something from L_T to something like L/T?
Thanks
In case of BA to B.A do something like this:
SELECT LEFT(YOURCOLUMN, 1) + '.' + RIGHT(YOURCOLUMN, 1) FROM YOURTABLE
And for the other one I will let you guess :)
For the second part use
SELECT REPLACE(YOURCOLUMN, '_', '/') AS YOURCOLUMN
This will replace any instance of _ with / in results for the selected column. If you exclude the AS YOURCOLUMN the row name in the results would be replace(YOURCOLUMN, '_', '/')
You can do this by using php
$db_cecord = "BA";
$formatted = implode('.',str_split($db_record));
This will result in B.A

PHP running MySQL query

So let me give you some information, i have a blog system which is backed to a database, the database holds the title of the articles. Now i have tried to create a "related news" feature, and it is rather basic, it just takes the title of the existing page and splits it up like so (Note that $row_object_title is just the title pulled from the database):
$row_object_title_lower = strtolower($row_object_title);
$keywords = explode(" ",$row_object_title_lower);
I then run it through my function:
exclude_conjuctions($keywords);
code for that function(looks for certain words and removes it from the array:
function exclude_conjuctions($array){
global $keywords_new;
$keywords_new = $array;
$conjuctions = array("here","to","and","but","or","nor","for");
$counter = count($keywords_new);
foreach($conjuctions as $conjuction){
for($i=0;$i <= $counter;$i++){
if ($keywords_new[$i] == $conjuction){
unset($keywords_new[$i]);
}
}
}
return $keywords_new;
}
So now i will build my query to retreive all articles that have the keywords in the title:
$sql = '';
foreach ($keywords_new AS $keyword)
{
if ($sql != '')
$sql .= ' OR ';
$sql .= "object_title LIKE '%$keyword%'";
}
$squery = 'SELECT object_title FROM example_table WHERE '.$sql;
NOW. It seems to be working okay, but there are times when it returns a title which does not have the same words as the current article, so i investigated it and it seems it picks up parts of the word and returns it, which is of course not what we want, if you are confused take a look at this image:
http://puu.sh/7UhhW.jpg
Note how i search for "dow" and those letters are found in both the current title and the retrieved titles. Of course i need it to only return related articles that have the full words in the title, not part of the words. What am i doing wrong guys? maybe my MySQL query needs to be changed? maybe there is a better solution? would love some help.
This is a problem as you can imagine.
Thanks for the help in advance.
Try doing LIKE '% {$keyword} %'
Also your query is vulnerable for SQL Injections.
How can I prevent SQL injection in PHP?
EDIT : A better way to do this would be using a Regular Expression:
REGEXP '[[:<:]]{$keyword}[[:>:]]'
Instead of LIKE...
Try using the === operator instead of the == operator to compare strings. A good reason why can be found here
Also, you are wrapping your query with % on each side. That says to return all matches that CONTAIN those strings. Thus 'Dow' is contained in 'Down' and would be returned. You probably want to add a space around the %'s to only get matches that equal your keywords.
Could you implement the "LIKE" search to include a preceding and succeeding space? You would possibly need to have three conditions though to cater for words at the start and end of sentence:
$sql .= "object_title LIKE '% $keyword %' OR LIKE '$keyword %' OR LIKE '% $keyword'";

Add string before and after array values for php>mysql searching

I have an html form with multiple checkboxes. I pass those to php...
The values will come in like "G,BW" for example ("BW,G" needs to match as well)
in check.php, I need to take the values from $_GET and modify them for an sql query...
<?php
if(!empty($_GET['wireColor'])) {
foreach($_GET['wireColor'] as $colors) {
echo $colors; //make sure it's right, then comment out
}
}
$colors = rtrim($colors, ','); //Get rid of trailing , - not working right
$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\''; //Trying to add the sql bits to pass to the query.
Ideally to get this passed:
$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' and wire_colors REGEXP '.*(^|,)$wireSearch(,|$)' );";
Here's how the query should look at the end:
SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)G(,|$)' and wire_colors REGEXP '.*(^|,)BW(,|$)' );
I'm having a hard time getting the regex bits into the query.
UPDATE
Here's what I have now:
<?php
if(!empty($_GET['wireColor'])) {
foreach($_GET['wireColor'] as $colors) {
$wireSearch = ' REGEXP \'.*(^|,)' .$colors.'(,|$)\' AND ';
}
}
$Search = rtrim($wireSearch, 'AND'); //Trying to trim the last "AND"
$colors_lookup_sql = "SELECT * FROM parts WHERE ( wire_colors $wireSearch% );";
Which gives me mostly what I need, but print/echo the results and I get:
$wireSearch ends up as: REGEXP '.*(^|,)G(,|$)' AND REGEXP '.*(^|,)BW(,|$)' AND Which is great - I just need to nuke the last "AND". The trim above replaces it with the second value instead though. Weird.
and $colors_lookup_sql ends up as: SELECT * FROM parts WHERE ( wire_colors REGEXP '.*(^|,)BW(,|$)' AND % );
BUt for some reason the first value in the array goes away, which I don't understand since it was present before the sql statement.
I'm not sure about the REGEX inside the query since I haven't used it but:
$wireSearch = '\'REGEXP \'.*(^|,).$wireColor.(,|$)\'';
Here you have a problem, the variable $wireColor is inside a string, and you are using ' so anything inside is not read as a variable, it should be something like:
$wireSearch = '\'REGEXP \'.*(^|,)'.$wireColor.'(,|$)\'';
I cant say I entirely understand how your data is being stored, and I havent worked with REGEX much myself, but perhaps something like this would be a bit easier to work with:
$wireSearch = explode(",", $_GET['wireColor']);
$query = "SELECT * FROM parts WHERE wire_colors LIKE '%$wireSearch[0]%'
AND wire_colors LIKE '%$wireSearch[1]%'";
Not sure if this helps but I thought id throw in the idea.
I guess mysql regex supports word boundaries, how about:
wire_colors REGEX '\bBW\b' and wire_colors regex '\bW\b'

Trim extra space from column Mysql

I have a old database in which column categories is stored in bad shape ... with extra space in them, example
Hotels in London
Hotels in Manchester
is there a way i can alter this space inside the table ... if i can remove extra space from categories (middle space) to get output like this
Hotels in London
Thx
You can use the REPLACE function like
update table set columnName= REPLACE(columnName,' ',' ')
Pull the data down into values that you can do work on then remove the extra white space using:
$foo = trim(preg_replace( '/\s+/', ' ', $foo ));
then write it back to the DB.
I had the similar situation where i had to remove the extra spaces while searching value for a particular field.
I have used replace function of mysql, like this
SELECT * FROM `tableName` WHERE post_id = 'xxx' AND replace(`fieldName`,' ','') Like '%JobOppurtunity%' ;
Here what replace does, it recursively removes all the spaces in the fieldName and concatenates the field value and then searches my concatenated string after LIKE keyword.
So if I had field value 'Job Oppurtunity', it will convert it into 'JobOppurtunity' and obviously I would have already concatenated my search string by any string function or regular expression. Like it did this way
$txt_search_qry = trim(preg_replace( '/\s+/', '', $txt_search_qry));
Another quick and simple method I found is this:
REPLACE(REPLACE(REPLACE(columnName,' ',' !'),'! ',''),' !',' ')

How to check if a string already exists in mysql (All word order options)?

Let's say i check if
$strig = "how can i do this";
already exists in my database with all words order options?
Like:
"how i can do this"
or
"i do this can how"
...
...
my database looks like:
id string
1 how can i do this
2 hello how are you
3 how i can do this world
4 another title
etc etc
Thanks
The number of possible combinations is n! (120 in your sample) so checking if this string already exists is quite complex task.
I would recommend to use the following algorithm:
Add new column StringHash to your table
On insert order your string (e.g. alphabetically), calculate its hash and store in StringHash:
"how can i do this" => "can do how i this" => md5("can+do+how+i+this")
If you want to check if a certain string exists in the db then again calculate its hash as described above and query the db on YourTable.StringHash
This is a tricky problem if you want to fix this in sql only, but that aside:
As #er.anuragjain says, you can do a query with LIKE %word%, but you would also get a hit on your example '3'.
So if you have a query like this:
SELECT * FROM table WHERE
column LIKE '%how%'
AND column LIKE '%can%'
AND column LIKE '%i%'
AND column LIKE '%do%'
AND column LIKE '%this%'
Then you also get number 3. So you need to check if there are no other words. You can do this by checking the word count (if you have 5 words and all of your words are in there, you are done.).
Checking wordcount is not trivial, but there is a trick. From several sources*:
SELECT LENGTH(total_words) - LENGTH(REPLACE(total_words, ' ', ''))+1
FROM tbl_test;
should do the trick. So check the LIKE's, and check the wordcount, and you're done. But I'm not really sure this is a pretty sollution :)
http://www.webtechquery.com/index.php/2010/03/count-number-of-words-in-mysql-mysql-words-count/
and http://www.mwasif.com/2008/12/count-number-of-words-in-a-mysql-column/
(random google hits :) )
you can ask if the string where you are searching in, contains: "how" and "can" and "I" and "do" and "this"
something like this:(I don't know the syntax in mysql but see the concept)
if(string.contain("how")&&
string.contain("can")&&
string.contain("I")&&
string.contain("do")&&
string.contain("this"))
{
//you find the string
}
If you are using mysql then try this..
select * from tablename where columnname Like '%how%' AND columnname LIKE '%can%' AND columnname LIKE '%I'% AND columnname LIKE '%DO'% AND columnname LIKE '%This'%;
Here if u have dynamic value in $string then first convert it into an array spliting by space.then create a $condition varriable from the array and append that in select * from tablename where and run that query.
thanks
should be the wildcard call in mysql
select * From tablename Where columnname LIKE '%how%'
you can use regex first crate a function like this
public function part($str){
$str = str_replace('‌',' ',$str);
$arr = explode(' ',$str);
$rejex = '';
foreach($arr as $item){
$rejex .= "(?=.*$item)";
}
return $rejex;
}
and then use sql regex
$sql = "SELECT * FROM `table` WHERE `column` REGEXP ".part($str);

Categories