2

I have a single page application. Select boxes need to be filled with select queries from the database.

How do I structure the application?

Currently I have a file add_details.php. It contains a HTML form with select queries to fill select boxes and if a user submits a form.

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    // Code for inserting data 
}

The below code is executed all in one page.

Should I separate and create a PHP file for insert and a PHP file to get results from the database?

I find separating things makes things cleaner but results in far too many files being created for select queries and inserts.

I use require_once 'SELECT query file' to populate the select boxes is there any easier way to do the above? is it necessary to create a a separate select query file?

2

Should I separate and create a PHP file for insert and a PHP file to get results from the database?

First, you may separate your data access from the business logic by moving data access code to a data access layer. For instance, if the select boxes are populated with the list of countries, then you'll have to call:

$this->db->listCountries();

from your business logic instead of doing directly the PDO stuff and the actual select ... from.

The next step is to consider what should be done with the business logic which is processing the submission of the form. You might decide that this is totally independent from the code which populates the form, in which case a separate file makes sense; however, in most cases, you'll consider that both actions are related, and keep them in the same file.

From your question, I'm not sure how advanced you are in application architecture, so if you don't know the following concepts, make sure you learn them:

You may also be interested in using a framework (especially in PHP). Laravel looks promising and encourages you to use MVC.

I use require_once 'SELECT query file' to populate the select boxes

While including files with require_once is a viable approach, it may be difficult to maintain the list of files to include. What if you rename a file which is included in a few dozen of files? What if you forget to remove an include to a file you don't use any longer?

This is why often autoloading is used instead: with autoloading, you don't have to import anything manually, and it just works, magically. You may also be interested by PSR-4 (or PSR-0 if you don't use namespaces in your project).

  • hi well I require the file for select query that contains code for getting rows from the database and filling up the select box.Is doing things in one file not recommended? – AAB Mar 12 '15 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.