PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Basically what you want to do is remove all the database stuff from your code. Put it on a different class. I call them managers.
The manager is the one that knows how an object relates to tables in a database. An object could be saved in 1 table or 3 tables. Your code should not need to know that. Thats why you put that logic somewhere else. In this case in the manager. Your manager will be something like this
class CustomerManager
{
function getNameKV()
{
//get data from database and put it into an array
}
}
Then just use a library to hide all the code from going through the array and selecting the right option. You are going to be doing this so many times that you dont want to repeat this code everywhere. It makes your code harder to read.
Design Patterns give you layers of abstraction that hide away detail of the underlying database from users, making it easier to modify database structure and the code within your pages are as a result much cleaner. In the example code you posted, if you ever had to change a variable name or some of the database structure you'd have a bit of a nightmare attempting to amend all of the code especially in much larger projects.
It's a more advanced concept but will benefit you much much more if you get to grips with it early.
If you have a lot of database tables you can even use the following code generator to automatically create the code you want:-