php & mysql - is there a better way to do this?
php & mysql - is there a better way to do this?
Author
Discussion

TonyRPH

Original Poster:

13,546 posts

199 months

Wednesday 19th February 2020
quotequote all
I have a database of HiFi equipment (just my own personal collection - not commercial) and I have a form which allows for 3 queries.

I can query on make, model or type.

I have this working - however - it's not quite 100% and I don't know where to go from here.

I would like to be able to query on make OR model OR type (either input field can be empty but at least one field must be populated of course).

If I provide at least 2 input fields, I only want those two specific fields to be queried.

However, I would like to be able to query something like; WHERE make LIKE %make% AND Model LIKE %model% etc..

Now I know I could do this with 'if 'or even 'case' statements - but is there a better way?

My query code looks like this;

code said:
if (!empty($make)) {
$query_string = "SELECT Make, Model, Type, Status, Notes, Value, Location FROM hifi_inventory WHERE (Make LIKE '%$make%') order by Make asc";
} else {
if (!empty($model)) {
$query_string = "SELECT Make, Model, Type, Status, Notes, Value, Location FROM hifi_inventory WHERE (Model LIKE '%$model%') order by Make asc";
} else {
if (!empty($type)) {
$query_string = "SELECT Make, Model, Type, Status, Notes, Value, Location FROM hifi_inventory WHERE (Type LIKE '%$type%') order by Make asc";
}
}
}
TIA!

Jakeztx

85 posts

137 months

Wednesday 19th February 2020
quotequote all
Just simplify it, if the fields are blank itll just search like '%null%' surely?

code said:
$query_string = "SELECT Make, Model, Type, Status, Notes, Value, Location FROM hifi_inventory
WHERE (Make LIKE '%$make%')
AND (Model LIKE '%$model%')
AND (Type LIKE '%$type%')
order by Make asc"

TonyRPH

Original Poster:

13,546 posts

199 months

Wednesday 19th February 2020
quotequote all
Jakeztx said:
< helpful stuff>
Thanks, that works a treat!

I guess I was over thinking it a bit!

beer


Jakeztx

85 posts

137 months

Wednesday 19th February 2020
quotequote all
Good stuff! Glad SOME things transfer between Oracle and MySQL