Jump to content
Queen_Gheek

Help with PHP form Validation

Recommended Posts

Hello All,

I am a newbie to PHP and I'm working on a marathon sign up form for my final project and could really use the help. The trouble i'm having is sending and retrieving database from the database. Below is the code i am using. Can someone please review and tell me where I went wrong.

 

(This is the code that is sitting at the top of my document)

<?php
session_start();
require_once('inc/dbuser.php');
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
if (isset($_POST['submit_registration'])) {
$username = test_input($_POST['username']);
$password = test_input($_POST['password']);
$cpassword = test_input($_POST['cpassword']);
$fname = test_input($_POST['fname']);
$lname = test_input($_POST['lname']);
$email = test_input($_POST['email']);
$phone = test_input($_POST['phone']);
$address = test_input($_POST['address']);
$city = test_input($_POST['city']);
$state = test_input($_POST['state']);
$zip = test_input($_POST['zip']);
$distance = test_input($_POST['distance']);
if (!empty($username) || !empty($password) || !empty($fname) || !empty($lname)|| !empty($email) || !empty($phone)|| !empty($address)|| !empty($city)|| !empty($state)|| !empty($zip)|| !empty($distance)) {

}
else{
    
     $sql = "SELECT email From runners Where email = ? Limit 1";
     //Prepare statement
     $stmt = mysqli_stmt_init($conn);
     if(!mysqli_stmt_prepare($stmt, $sql)){
       header("location: ../signup?error=sqlerror");
      exit();  
     }
     else{
     mysqli_stmt_bind_param($stmt,'s', $email);
     mysqli_stmt_execute($stmt);
     $stmt->bind_result($email);
     $stmt->store_result($stmt);
     $resultCheck = mysqli_stmt_num_rows($stmt);
     if ($resultsCheck > 0) {
      header ("Location: ../signup.php?error=usertaken&email=".$email);
      exit();
     }
     else {
         $sql = "INSERT Into runners (username, password, fname, lname, email, phone, address, city, state, zip, distance) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
         $stmt = mysqli_stmt_init($conn);
         if(!mysqli_stmt_prepare($stmt, $sql)) {
             header ("Location: ../signup.php?error=sqlerror");
      exit();
         }
         else{
            $hashedPwd = password_hash($password, PASSWORD_DEFAULT);
         mysqli_stmt_bind_param($stmt,"ssssssssssss", $username, $hashedPwd, $fname, $lname, $email, $phone, $address,$city, $state, $zip, $distance);
         mysqli_stmt_execute($stmt);
         header ("Location: ../signup.php?signup=success");
      exit();
         
 }
}
     }    
}
 mysqli_stmt_close($stmt);
     mysqli_stmt_close($conn);
}  
   
?>

 

(This is my form [submit_registration] )

 

<div class="contact">
                <?php
                if(isset($_GET['error'])) {
                    if($_GET['error']=="emptyfields"){
                       echo '<p>Fill in all fields!</p>';
                    }
                    elseif($_GET['error']== "invalidemail") {
                       echo '<p>Provide a valid email!</p>';  
                    }
                    elseif($_GET['error']== "usertaken") {
                       echo '<p>Username is already taken!</p>';
                    }
                     elseif($_GET['error']== "passwordCheck") {
                       echo '<p>Your passwords do not match!</p>';
                     }
                      elseif($_GET['signup']== "success") {
                       echo '<p>Signup Successful!</p>';
                      }
                }
                ?>
            <form name="form1" action="signup.php" method="post">
                            <p><label>Create a username:<br></label>
                                    <input type="text" name="username" placeholder="username" autofocus required><br>
                                    <span class="err" id="usrErr"></span>
                                </p>
                                <p><label>Create a Password:<br></label>
                                    <input type="password" name="password" placeholder="password" autofocus required><br>
                                    <span class="err" id="pwdErr"></span>
                                </p>
                                <p><label>Confirm Password:<br></label>
                                    <input type="password" name="cpassword" placeholder="confirm password" autofocus required><br>
                                    <span class="err" id="cpwdErr"></span>
                                </p>
                                <p><label>First Name:<br></label>
                                    <input type="text" name="fname" placeholder="first name" autofocus required><br>
                                    <span class="err" id="fnErr"></span>
                                </p>
                                <p><label>Last Name:<br></label>
                                    <input type="text" name="lname" placeholder="last name" autofocus required><br>
                                    <span class="err" id="lnErr"></span>
                                </p>
                                <p><label>Email:<br></label>
                                    <input type="text" name="email" placeholder="you@youremail.com" required><br>
                                    <span class="err" id="emErr"></span>
                                </p>
                                <p><label>Phone: <br></label>
                                    <input type="tel" name="phone1" placeholder="XXX-XXX-XXXX" maxlength="13" required>
                                    <span class="err" id="phErr"></span>
                                </p>
                                <p><label>Address: <br></label>
                                    <input type="text" name="address" placeholder="415 W. 15th Street" required>
                                    <span class="err" id="addErr"></span>
                                </p>
                                <p><label>City: <br></label>
                                    <input type="text" name="city" placeholder="Chicago" required>
                                    <span class="err" id="cityErr"></span>
                                </p>
                                <p><label>State:<br></label>
                                    <input type="text" name="state" placeholder="IL" maxlength="2" required>
                                    <span class="err" id="stateErr"></span>
                                </p>
                                <p><label>Zip: <br></label>
                                    <input type="text" name="zip" placeholder="60621" maxlength="5" required>
                                    <span class="err" id="zipErr"></span>
                                </p>
                                <p>I am interested in:<br>
                                <span id="inErr" class="err"></span>
                                <select id="interest" class="adj">
                                    <option disabled>--5k--</option>
                                    <option> 1 Mile Run</option>
                                    <option> 5K Run</option>
                                    <option>10K run</option>
                                </select>
                                </p>
                                  <button type="submit" name="submit_registration"onclick="validForm()">Signup</button>
 
                                  
                                </p>
                            </form>

Share this post


Link to post
Share on other sites
Posted (edited)

First please use the code icon (<>) for your code and specify PHP and HTML as appropriate. What you omitted from your post is what error are you getting or what are you getting that is different from what you expect?

Edited by gw1500se

Share this post


Link to post
Share on other sites
4 minutes ago, gw1500se said:

First please use the code icon (<>) for your code and specify PHP and HTML as appropriate. What you omitted from your post is what error are you getting or what are you getting that is different from what you expect?

Thank you for responding! My issue is that my data isn't inserting into the database.

 <?php
session_start();
require_once('inc/dbuser.php');
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
if (isset($_POST['submit_registration'])) {
$username = test_input($_POST['username']);
$password = test_input($_POST['password']);
$cpassword = test_input($_POST['cpassword']);
$fname = test_input($_POST['fname']);
$lname = test_input($_POST['lname']);
$email = test_input($_POST['email']);
$phone = test_input($_POST['phone']);
$address = test_input($_POST['address']);
$city = test_input($_POST['city']);
$state = test_input($_POST['state']);
$zip = test_input($_POST['zip']);
$distance = test_input($_POST['distance']);
if (!empty($username) || !empty($password) || !empty($fname) || !empty($lname)|| !empty($email) || !empty($phone)|| !empty($address)|| !empty($city)|| !empty($state)|| !empty($zip)|| !empty($distance)) {

}
else{
    
     $sql = "SELECT email From runners Where email = ? Limit 1";
     //Prepare statement
     $stmt = mysqli_stmt_init($conn);
     if(!mysqli_stmt_prepare($stmt, $sql)){
       header("location: ../signup?error=sqlerror");
      exit();  
     }
     else{
     mysqli_stmt_bind_param($stmt,'s', $email);
     mysqli_stmt_execute($stmt);
     $stmt->bind_result($email);
     $stmt->store_result($stmt);
     $resultCheck = mysqli_stmt_num_rows($stmt);
     if ($resultsCheck > 0) {
      header ("Location: ../signup.php?error=usertaken&email=".$email);
      exit();
     }
     else {
         $sql = "INSERT Into runners (username, password, fname, lname, email, phone, address, city, state, zip, distance) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
         $stmt = mysqli_stmt_init($conn);
         if(!mysqli_stmt_prepare($stmt, $sql)) {
             header ("Location: ../signup.php?error=sqlerror");
      exit();
         }
         else{
            $hashedPwd = password_hash($password, PASSWORD_DEFAULT);
         mysqli_stmt_bind_param($stmt,"ssssssssssss", $username, $hashedPwd, $fname, $lname, $email, $phone, $address,$city, $state, $zip, $distance);
         mysqli_stmt_execute($stmt);
         header ("Location: ../signup.php?signup=success");
      exit();
         
 }
}
     }    
}
 mysqli_stmt_close($stmt);
     mysqli_stmt_close($conn);
}  
   
?> 

 

This is my html form

 

<div class="contact">
                <?php
                if(isset($_GET['error'])) {
                    if($_GET['error']=="emptyfields"){
                       echo '<p>Fill in all fields!</p>';
                    }
                    elseif($_GET['error']== "invalidemail") {
                       echo '<p>Provide a valid email!</p>';  
                    }
                    elseif($_GET['error']== "usertaken") {
                       echo '<p>Username is already taken!</p>';
                    }
                     elseif($_GET['error']== "passwordCheck") {
                       echo '<p>Your passwords do not match!</p>';
                     }
                      elseif($_GET['signup']== "success") {
                       echo '<p>Signup Successful!</p>';
                      }
                }
                ?>
            <form name="form1" action="signup.php" method="post">
                            <p><label>Create a username:<br></label>
                                    <input type="text" name="username" placeholder="username" autofocus required><br>
                                    <span class="err" id="usrErr"></span>
                                </p>
                                <p><label>Create a Password:<br></label>
                                    <input type="password" name="password" placeholder="password" autofocus required><br>
                                    <span class="err" id="pwdErr"></span>
                                </p>
                                <p><label>Confirm Password:<br></label>
                                    <input type="password" name="cpassword" placeholder="confirm password" autofocus required><br>
                                    <span class="err" id="cpwdErr"></span>
                                </p>
                                <p><label>First Name:<br></label>
                                    <input type="text" name="fname" placeholder="first name" autofocus required><br>
                                    <span class="err" id="fnErr"></span>
                                </p>
                                <p><label>Last Name:<br></label>
                                    <input type="text" name="lname" placeholder="last name" autofocus required><br>
                                    <span class="err" id="lnErr"></span>
                                </p>
                                <p><label>Email:<br></label>
                                    <input type="text" name="email" placeholder="you@youremail.com" required><br>
                                    <span class="err" id="emErr"></span>
                                </p>
                                <p><label>Phone: <br></label>
                                    <input type="tel" name="phone1" placeholder="XXX-XXX-XXXX" maxlength="13" required>
                                    <span class="err" id="phErr"></span>
                                </p>
                                <p><label>Address: <br></label>
                                    <input type="text" name="address" placeholder="415 W. 15th Street" required>
                                    <span class="err" id="addErr"></span>
                                </p>
                                <p><label>City: <br></label>
                                    <input type="text" name="city" placeholder="Chicago" required>
                                    <span class="err" id="cityErr"></span>
                                </p>
                                <p><label>State:<br></label>
                                    <input type="text" name="state" placeholder="IL" maxlength="2" required>
                                    <span class="err" id="stateErr"></span>
                                </p>
                                <p><label>Zip: <br></label>
                                    <input type="text" name="zip" placeholder="60621" maxlength="5" required>
                                    <span class="err" id="zipErr"></span>
                                </p>
                                <p>I am interested in:<br>
                                <span id="inErr" class="err"></span>
                                <select id="interest" class="adj">
                                    <option disabled>--5k--</option>
                                    <option> 1 Mile Run</option>
                                    <option> 5K Run</option>
                                    <option>10K run</option>
                                </select>
                                </p>
                                  <button type="submit" name="submit_registration"onclick="validForm()">Signup</button>
 
                                  
                                </p>
                            </form> 

 

Share this post


Link to post
Share on other sites
45 minutes ago, Queen_Gheek said:

if (!empty($username) || !empty($password) || !empty($fname) || !empty($lname)|| !empty($email) || !empty($phone)|| !empty($address)|| !empty($city)|| !empty($state)|| !empty($zip)|| !empty($distance)) {

}
else{
    

which translates to

if (one or more of the fields has something in it) 
{
    // do nothing
}
else 
{
    // process the data
}

It is far better to put a unique constraint on your email column and then insert the record to see if it fails with a duplicate key error..

  1. it saves a query to see if it's there
  2. Just because you didn't find it doesn't mean it won't be there when you do your insert (some could have beaten you to it).

Share this post


Link to post
Share on other sites

the mistake is probably at the binding/execution for the insert query. i won't mention what i saw because it is more important that you develop simple coding that will either work or it will tell you (display/log) why it isn't working. because you have no useful error handling for all the database statements that can fail (connection, query, prepare, and execute) and probably don't have php's error related settings set up to get php to help you, you are not getting any feedback that would allow you to solve the problem yourself.

start by doing what was written here - https://forums.phpfreaks.com/topic/310992-mysqli-count-query-prepared-statements/?tab=comments#comment-1579137

 

next, this code is full of unnecessary things that don't add any value to what you are trying to accomplish (a form and form processing code that inserts data into a database table.) some recommendations that will result in simple code -

  1. put the form and the form processing code on the same page, with the form processing code above the start of the html document. this will allow you to directly display any validation errors and re-populate the form field values with the submitted data so that the user doesn't need to keep reentering the same things over and over.
  2. forget about that dumb test_input() function you found or were given. the only thing it is doing that's appropriate is trimming the data. everything else is either wrong for the context or needs to be conditionally applied.
  3. you should not test if the submit button isset. there are cases where it won't be. you should instead test if a post method form was submitted.
  4. don't write out line after line of code for each form field. just keep the set of form data as an array, then operate on elements in the array in the rest of the code. this will lead to dynamically validating and processing the submitted form data, further simplifying the code.
  5. validate all inputs separately, setting up a unique and helpful error message for each validation error, storing the validation errors in an array, using the form field name as the array index. this array is also an error flag. if there are no errors, it will be empty, and you can use the submitted form data. you can also test/display the contents of this array at the appropriate location in the html document. 
  6. as has already been stated, your database definition must enforce unique entries. since it must do this to prevent duplicates, there's no good reason for the extra code/query to try to select the data first. just attempt to insert it, then detect if a duplicate key error occurred. this is also mentioned at the linked to forum reply.
  7. if you switch to the much simpler and more consistent PDO extension, over half of the database related statements will go away, which will eliminate the mistake i saw, because you don't have to produce multiple statements with things in them for each column in a query.
  8. in most cases, you don't need to close prepared statements or close database connections, since php will automatically do this for you when you script ends.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.