PHP "Form" best practice?

Using PHP I will have a form with about 50 fields on it.

One way to get to the page/form is to search by item ID.  If found the page will come up and the form will fill with existing data.

I would like to utilize the same page/form to "create" items.

What would be a good way to do this?

One way is to set each DB field to a variable and then populate the form using the variables.  For "new" items I would simply set the variables to defaults (usually blank or empty).

Is this about the only way?
Sheldon LivingstonConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
I would do it like this

<!DOCTYPE html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
 <div id="editItem">
     <!-- edit form code here -->  
  <button id="new">New</button>
<div id="modal">
  <!-- new form here -->  

Open in new window

The edit form is created dynamically and populated by your database.  The new form is hidden in a modal. When you click the New button, the modal appears and you can create your new item.
Zakaria AcharkiAnalyst DeveloperCommented:
IMO it will be better to use the Object Oriented Programming in this case.

By creating a class for your table you don't have to create all those variables you will get one object contains all the table attributes.

Example : let say you've an object Student for your tables students in the database it will be easy for you to attach them attributes to the form field whe you get your object from the DB like :

<input name="first_name" value="<?php echo $student->first_name; ?>">
<input name="last_name" value="<?php echo $student->last_name; ?>">

Open in new window

For the new form, the call of attributes will remain the same (so form body will be the same for the "new/edit" actions) but the object will be just instanciated with empty values (you've to set this in you constructor) :

$student = new Student();

Open in new window

I will recommend to you the use of a PHP framework if you can, that will make your life easier. else you need to follow some tutorials in PHP OOP connecting with DB tables, If you choose this approach let me know to provide some links for you.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Sheldon LivingstonConsultantAuthor Commented:
Thank you guys... I'll be looking at OOP.  Zakaria... can you provide some links please?
Julian HansenCommented:
There are other options

If you want to go the render route then typically you set up helper functions to render out fields. For example

$form->addInput('name', $data);

Open in new window

This would then do something like
function addInput($name, $data=[])
   $value = isset($data[$name]) ? $data[$name] : ''
   echo <<< INPUT
    <input type="text" name="data[{$name}]" value="{$value}">

Open in new window

Before calling this you would
With the above you can pass anything you like to the field generator. If you are editing a record pass in the data value - the generator add it to the rendered field. If you are adding a new record then pass an empty array - the generator will handle this for you.

You can add as many field generators as you need and expand the options to handle things like required / disabled etc.

Another thing to take note of with the above with is the name of the field. Note how we are using array notation for the variables.

This is useful in processing the form data when it comes in. You need to do one call
$data = isset($_POST['data']) ? $_POST['data'] : false;
$errors = validateData($data));
if (empty($errors)){
   // form is good
else {
  // set errors and render form for re-submission

Open in new window

This allows you to keep database data separate from meta data you might want to submit with the form.

Personally I find the gymnastics required for manipulating form rendering on the server with all the combinations of new / edit / valid / not valid overly complex. I much prefer to render the form out as a vanilla form and then in the client make an API call to fetch the data (using AJAX) which is then injected into the form.

The big advantage with doing it this way is that the form gets rendered once by a single function - the logic around errors , validation, populating, emptying saving etc are all handled in the client with AJAX calls to an API to validate / save / retrieve data.

By using intelligent naming conventions you can write very generic code that will do all the operations with surprisingly few lines of code. It also means that your API functions are dead simple as they don't have to deal with the API.
Zakaria AcharkiAnalyst DeveloperCommented:
You're welcome @Sheldon

Take a look at this answer it has a simple example using the PDO to connect your DB with OOP (How to use PDO connection with OOP) you will find a link at the end of the post for further information.

You may found this series of videos about OOP Crud using PDO helpful.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.