php - Create MySql query for search functions -


i have problem query search function in site. have table saving book data , in frontend page have search function find book search parameters.

this database table :

book_id | book_name       | book_location | book_qty | book_date ----------------------------------------------------------------- 1       | triangle math   | rack1         | 2        | 2017-06-12 2       | basic knowledge | rack2         | 3        | 2016-08-09 3       | legend truth    | rack3         | 1        | 2014-05-17 4       | temporary brain | rack4         | 1        | 2013-01-23 

and search in frontend page :

1. input field book name -- $name 2. dropdown list book location -- $location 3. search button 

the 4 parameters above variable use in query search result.

i tried query not give me best result want.

select * `book` book_name '%".$name."%' or book_location = '".$location."' 

when choose location in dropdown list , leave field book name empty example choose rack1 got result data shown. want data have book_location in rack1. after var_dump() query realize got query :

select * `book` book_name '%%' or book_location = 'rack1' 

and know query data because book_name like '%%'.

what want ask how make best query search if not parameters in search function not filled ? thank you.

just check if $name empty, execute appropriate query:

if ($name !== "") {     // select * `book` book_name '%".$name."%' or book_location = '".$location."' } else {     // select * `book` book_location = '".$location."' } 

you can in 1 query if use short-circuit condition:

select * book (".$name." != "" , book_name '%".$name."%') or book_location = '".$location."'; 

that check second operand if first 1 true ($name not empty)


as warning, seem vulnerable sql injections. use prepared statements!


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -