简体   繁体   中英

php MySQL Search on two columns

I'm trying to do a search function using php and MySQL. I need to search from two different columns, one for song title and one for artist and user can search using:

1. artist name.
2. song title.
3. both of them (without order)
4. there will be special characters for ex: ' (apostrophe)

This is what I have done but I need a more efficient way to do this. I have also thought using similar_text(); in php. Can anyone suggest me a better way to do this. Thank You

table: songs

|artist   |    title   |
|----------------------|
|eminem   | not afraid |
|kida     | o'najr     |

My code:

$search_value = $_POST["search_value"];
$query = "select * from `songs` where concat(`title`, `artist`) like '%$search_value%'";

You can simply use sql or statement if you don't want confusion .

$search_value = $_POST["search_value"];//check user input first than create a query.
$query = "select * from `songs` where `title` like '%$search_value%' or  `artist` like '%$search_value%'";
  1. You should use the SQL OR statement, better than CONCAT one in this case.

  2. Combined with a space before and after what you search, this should give you the expected result ! (I mean if you search for 'raid' you will not find 'Eminem - Not Afraid', if you want to find it you have to search for 'afraid' for exemple ; If you want to sort the results by revelance, you will have to create indexes and use them, or use Levenshtein method or something else ...)

  3. Don't forget to escape your data before using it in sql statements.

Btw if you want to make it case insesitive you will have to use blabla COLLATE UTF8_GENERAL_CI LIKE %what you search% blabla

// if you are using mysql_connect()
$search_value = ' '.mysql_real_escape_string($_POST["search_value"]).' ';
$query = "select * from `songs` where `title` like '%$search_value%' or  `artist` like '%$search_value%'";

// if you are using PDO
$args[':search_value'] = '% '.$_POST["search_value"].' %';

$query = "SELECT * FROM `songs` WHERE `title` LIKE :search_value OR `artist` LIKE :search_value";

$qry = $PDO->prepare($query);
$res = $qry->execute($args);

For a multi-words search you can also use

// for mysql_connect()
$search_value = $_POST["search_value"];
$search_value = explode(' ', $search_value);
foreach($search_value as $k => $v){
    $search_value[$k] = mysql_real_escape_string($v);
}
$search_value = ' '.implode(' % ', $search_value).' ';

// for PDO
$search_value = explode(' ', $_POST["search_value"]);
$search_value = implode(' % ', $search_value);
$args[':search_value'] = '% '.$search_value.' %';

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM