Skip to content
Advertisement

Form Processing php

I am new here so please point me in the right direction if I am misunderstanding how to submit a question here.

1. I am getting warning errors stating that I have “Undefined array keys”. I get this before and after the form has been submitted. I have defined the arrays at the top so I am unsure why they are undefined.

2. My error trapping is not working if I enter an incorrect phone number format. I initially get the error stating to put it in the right format, but if I put the information in the correct format and submit I still get the error and the phone number resets to what it was initially. I am getting that it is pulling it from the $_GET, but not sure why when it is submitted again it is not updating the $_GET to populate it correctly.

JavaScript

Advertisement

Answer

Okay, so a few things here:

  • You don’t need the variable assignations at the top. This is something very important in C and other languages, but PHP doesn’t require this.

  • Your if(isset($_GET['firstName'])) $firstName = $_GET['firstName']; statements are using $_GET while your <form> tag uses $_POST – that’s your main issue

  • I would recommend using an array of variables, something like this:

    JavaScript

Then you can output the fields programmatically like this:

JavaScript

This not only cleans up the code quite a bit, but it also makes it much, much easier (and safer) to change/update or even add to the fields.

Then, to validate the fields you can use the validation array key I set up as a switch to go through all your fields. Something like this:

JavaScript
  • You didn’t wire up your product fields correctly. There’s no way for the user-submitted value to ‘stick’ here, so the field’s value is simply lost. To begin with, we can put these all in an array, similar to what we did with the address fields:

    $product_vars = array( array( ‘element_name’ => ‘band’, ‘title’ => ‘Band’, ‘options’ => $bands, ‘placeholder’ => ‘Choose One’, ), array( ‘element_name’ => ‘color’, ‘title’ => ‘Color’, ‘options’ => $colors, ‘placeholder’ => ‘Choose One’, ), );

Then we can use the following for the form:

JavaScript

Hopefully this helps!

**EDIT DUE TO NEW CODE SHARED **

There were again a few things here. Main items were: the $product_vars foreach being outside the <form> tag, the <form> tag not being set to use $_POST despite the rest of the code being set that way, and not adding any validation types. I’ve pasted the full code I have, which is working for me.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement