[Solved] How to add new fields in my registration form [closed]


This is a very open-ended question. You’ll need code to handle adding the input to the database, but that warrants a separate question.

For the PHP, you’ll need to decide how to validate each field, and then add another if block for each question. For the HTML, you’ll need to add another input for each field.

Example Code

For date of birth, you should probably ensure that it’s a valid date. And then you may want to validate age as well.

You might use PHP code like this for birth date:

//test date
try {
    $max_date = new DateTime('13 years ago');
    $birth_date = new DateTime($_POST['birth_date']);
    if ($birth_date > $max_date) { {
        $errors[] = 'You must be at least 13 years old.';
    }
} catch (Exception $e) {
    $errors[] = 'Birth date is not a valid date.';
}

You could then use the following to format the date for MySQL:

$birth_date->format('Y-m-d');

Relevant PHP manual pages:

And you might use HTML code like this for birth date:

<h4>Birth Date:</h4>
<input type="text" name="birth_date" value="<?php if (isset($_POST['birth_date'])) echo htmlentities($_POST['birth_date']); ?>" />

You could also format the input into separate fields for each part of the date and use drop down menus. I don’t find this is necessary since the DateTime class can handle a wide variety of formats. However, I usually add a jQuery Datepicker to make it more user friendly.


Other Fields

The above should give you a good starting point. You can do something similar for each field. You need to show more personal effort if you expect people here to help.

If you have specific questions about how to validate the other inputs, you should post a separate question (after first searching for the answer). Show what you’ve tried. Describe the result and explain how it’s different from the expected result.


Suggestions for Code Improvement

  1. I’d combine the two if blocks for username. If the username already exists, you don’t need to validate the format.

    if ($users->user_exists($_POST['username']) === true) {
        $errors[] = 'That username already exists';
    } else if (!ctype_alnum($_POST['username'])) {
        $errors[] = 'Please enter a username with only alphabets and numbers';
    }
    
  2. Comparing the return value of empty($errors) to true or false is redundant. The return value is always a boolean. You only need if (empty($errors)) or if (!empty($errors)).

  3. You should use label elements in your HTML instead of h4 elements to make your HTML more semantic. You can then use CSS to style them however you want.

    <label for="fld-password">Password:</label>
    <input type="password" id="fld-password" name="password" />
    

5

solved How to add new fields in my registration form [closed]