I've started developing a project and I need use a advanced search query with PHP and Mysqli , but I'm getting some troubles. Check out below my query.
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE name LIKE '%".$filter."%' OR keybox LIKE '%".$filter."%' ORDER BY id LIMIT 0, 10";
It's working perfeclty! But still not matching entries that contains symbols, for example, if my database contains a row called "Color: red" and someone type "Color red" , the query will return empty, but if I type "Color: red" returns found. So, what should I do to resolve this issue?
Thanks
The one thing that I can think of in order to maintain consistency is that you can eliminate the ':' in your query for matching. Try the below query:
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE REPLACE(name, ':', '') LIKE '%REPLACE(".$filter.", ':', '')%' OR REPLACE(keybox, ':', '') LIKE '%REPLACE(".$filter.", ':', '')%' ORDER BY id LIMIT 0, 10";
Hope this helps.
Either use the REGEXP as:-
SELECT * FROM table WHERE columnName REGEXP "regular_expression";
or use REPLACE() function in WHERE clause as:-
SELECT * FROM table WHERE REPLACE(columnName, ":", "") LIKE "like_expression";
Use two queries to find exact and similar records. If the records available in Exact data query then no need to run the similar data query
<?php
//Fetches Exact Data
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE name LIKE '%".$filter."%' OR keybox LIKE '%".$filter."%' ORDER BY id LIMIT 0, 10";
//If the previous query doesn't return any value, then use
//Split the the user input and then query DB
$condition="name!=''";
$filters=explode(" ",$filter);
foreach($filters as $val)
{
$condition.=" or (name LIKE '%$val%' OR keybox LIKE '%$val%')";
}
//Fetches Similar Data
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE $condition ORDER BY id LIMIT 0, 10";
//-----------ENDS
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.