I need to speed up an sql query. Or handle the php code better. Some best practice when searching a database and displaying the result in the frontend.
Basically I have three tables
– boxes, that contains records
– records, that contains songs
– song
I would like my frontend code to list something like:
Box 1
-Record 1
--Song 1
--Song 2
etc....
-Record 2
--Song 1
--Song 2
etc....
Box 2
-Record 1
--Song 1
--Song 1
etc. etc. etc.
“My way” is very time consuming:
- I search the “Box” table using standard SQL.
- For each row I call a function that finds each record for that box
- For each record I call a function that finds each song for that record
It takes a loooong time to complete since the number of select calls is enormous (many boxes, many recors)
I guess there is a more easy way (from the servers pointy of view) to do the same. Pull dato to php arrays and to the logic there or something else that is clever.
Question:
What is the best practice to get data from a relational database using php?
Br. Anders
You need to learn about
JOINs. Here, you would use two outer joins. That way, you achieve the same result using only one select query, and the amount of work that has to be done by PHP and by MySQL is much less.Your SQL would look something like this: (Note that I use
SELECT *as a stand-in for the real list of columns, because I don’t know what columns you have – usingSELECT *is generally not a good idea)