PHP Registration Form Not Displayinf Correctly

I'm trying to implement a php client registration form following the script at: https://www.allphptricks.com/simple-user-registration-login-script-in-php-and-mysqli/

My problem is that registration.php is not displaying as expected:
(1) "You are registered successfully." is displayed on load before any user data is entered.
(2)"Click here to Login "; } else { ?> " is displayed instead of simply "Click here to Login".
(3) data entered into registration.php is not actually inserted in the database

php version; 5.6
Database name:  client_register
Table name: clients

Obviously, I have very brief understanding of php.  Any help would be great.

registration.php
<!doctype html>
  <html lang="en">
    <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <meta name="keywords" content="">
      <meta name="description" content="Master Form Component">
      <meta name="author" content="Price Learman | Palm Springs, CA">
      <title>Registration</title>

      <link rel="stylesheet" href="./_css/main.css" crossorigin="anonymous">

       <!--[if lt IE 11]>
      <a href="./browserUpdate.com"></a>
      <![endif]-->
    </head>

    <body>

      <?php
        require('database.php');
        // If form submitted, insert values into the database.
        if (isset($_REQUEST['username'])){
                // removes backslashes
          $username = stripslashes($_REQUEST['username']);
                //escapes special characters in a string
          $username = mysqli_real_escape_string($con,$username);
          $email = stripslashes($_REQUEST['email']);
          $email = mysqli_real_escape_string($con,$email);
          $password = stripslashes($_REQUEST['password']);
          $password = mysqli_real_escape_string($con,$password);
          $trn_date = date("Y-m-d H:i:s");
                $query = "INSERT into `clients` (username, password, email, trn_date)
        VALUES ('$username', '".md5($passwhttps://www.experts-exchange.com/askQuestion.jspord)."', '$email', '$trn_date')";
                $result = mysqli_query($con,$query);
                if($result){
                    echo "<div class='registration-form-wrapper'>
                            <h5>You are registered successfully.</h5>
                            <br/>Click here to <a href='login.php'>Login</a>
                          </div>";

                    } else {

            ?>



      <div class="registration-form-wrapper">
        <h5>New Client Registration</h5>
        <form  id="registration-form" name="registration-form" method="post" action="" >
          <div class="form-group">
           <!-- <label for="name" class="sr-only">Full Name</label> -->
           <input type='hidden' name='submitted' id='submitted' value='1'>
            <input
               type="text"
               class="form-control"
               id="username"
               name="username"
               aria-describedby="usernameHelp"
               placeholder="Enter Your User Name"
               required
               pattern="^[a-zA-Z0-9]{6,}$"
               data-valueMissing="Please enter your user name"
               data-patternMismatch="User name must be at least 6 alpha-numeric characters, no special characters"
               placeholder="Enter User Name"
            >
            <div id=usernameHelp class="help-text"></div>
          </div>

          <div class="form-group">
          <!--  <label for="email" class="sr-only">Email Address</label>  -->
            <input
               type="email"
               class="form-control"
               id="email" name="email"
               aria-describedby="emailHelp"
               required
               pattern="^.+@.+\..+[^.ru]$"
               data-valueMissing="Please enter your email"
               data-patternMismatch="Enter a valid email address, example: me@myhost.com"
               placeholder="Enter Email Address"
            >
            <div id=emailHelp class="help-text"></div>
          </div>

          <div class="form-group">
          <!--  <label for="password" class="sr-only">User Password</label>  -->
            <input
              type="password"
              class="form-control"
              id="password"
              name="password"
              aria-describedby="passwordHelp"
              required
              pattern="^[a-zA-Z0-9]{6,}$"
              data-valueMissing="Please enter a password"
              data-patternMismatch="Passwords must be a minimum of 6 alpha-numeric characters"
              placeholder="Enter Your Password"
            >
            <div id=passwordHelp class="help-text"></div>
          </div>

          <button type="submit" class="">Register</button>
        </form>
      </div>

    <?php } ?>

    </body>
  </html>

Open in new window


database.php
<!doctype html>
  <html lang="en">
    <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    </head>

    <body>

     <?php
      // Enter your Host, username, password, database below.
      // I left password empty because i do not set password on localhost.
      $con = mysqli_connect("localhost","root","","pricelea_client_register");
      // Check connection
      if (mysqli_connect_errno())
        {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    ?>

    </body>
  </html>

Open in new window

dlearman1Asked:
Who is Participating?

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

x
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.

Julian HansenCommented:
Rule 1. Messy code leads to errors and makes it difficult to debug.
Learn about HEREDOC and use it for your output that spans multiple lines.
Example
Instead of
echo "<div class='registration-form-wrapper'>
                  <h5>You are registered successfully.</h5>
                     <br/>Click here to <a href='login.php'>Login</a>
                          </div>";

Open in new window

Do
echo <<< HTML
<div class="registration-form-wrapper">
  <h5>You are registered successfully.</h5>
  <br/>Click here to <a href="login.php">Login</a>
</div>
HTML;

Open in new window

Note the neater formatting of the above and the use of double quotes for the attributes.

2. Look at lines 35-36 - you have a URL in the middle of $password
$query = "INSERT into `clients` (username, password, email, trn_date)
        VALUES ('$username', '".md5($passwhttps://www.experts-exchange.com/askQuestion.jspord)."', '$email', '$trn_date')";
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Open in new window


3. You are opening an if statement on line 25 that is not being closed

4. Don't use $_REQUEST. Use $_POST and make sure your data is posted to the form.
Why? Get URL's are cached and you don't want URL's with usernames in your CACHE. POST sensitive data

5. Don't assume that POSTED variables exist rather retrieve like so
$username = isset($_POST['username']) ? $_POST['username'] : false;

Open in new window

Now $username is guaranteed to have a value AND you can test if it was present

Let's start with that - fix those errors, neaten up your code - make sure all closing tags line up with their opening tags, statement blocks ({ }) line up.

Fix your $_REQUEST.

Post back when you have done that and see what issues there still are.
dlearman1Author Commented:
Julian
Thanks for your comments. I appreciate them.  

As I mentioned, I really don't know anything about php scripting. We use some purchased php components, but I have never had to get into the details. Slightly In my defense, this php code isn't mine but the author  of https://www.allphptricks.com/simple-user-registration-login-script-in-php-and-mysqli.

I have given the HEREDOC reference a quick read and it looks interesting. I will refer back to it, if necessary.

I gather that php parses single quotes and double quotes differently. True?

The "URL in the middle of password" was created by Sublime Text 3 auto "best completion feature."  I've been tripped up before if I wasn't watching the monitor.

I believe the author does close the if statement, but does so on line 109 so that the html code is encapsulated into the php. Is this a normal php construct?

Thanks for your advice on "Request vs Post" and username validity.  I will look for this feature in future php code.

Long story short, I'm probably going to use your information to make a smarter choice in selecting a log-in script.
Julian HansenCommented:
I gather that php parses single quotes and double quotes differently. True?
Yes.
Single quotes
- Double quotes don't need to be escaped
-  Single quotes (in string) do
- No variable interpretation

Double quotes
- Single quotes don't need to be escaped
- Double quotes (in string) do
- Variables are interpreted

HEREDOC - best of both worlds
- Both single and double quotes can be used without escaping
- Variables are interpreted

I believe the author does close the if statement, but does so on line 109 so that the html code is encapsulated into the php. Is this a normal php construct?
No, that closes the else on line 44 - or it closes line 25 but then leaves the else on 44 unclosed.

Long story short, I'm probably going to use your information to make a smarter choice in selecting a log-in script.
Some advice
All my login scripts run on AJAX.
Reason - logical separation of view and model / authentication logic means things are lot simpler.

I have a simple form with username and password.
Simple click event handler on the submit
AJAX to a server side script that validates and returns a true / false
JavaScript redirects to landing page.

When you start mixing PHP code and HTML it gets messy - I try to avoid that.

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
SolarWinds® Network Configuration Manager (NCM)

SolarWinds® Network Configuration Manager brings structure and peace of mind to configuration management. Bulk config deployment, automatic backups, change detection, vulnerability assessments, and config change templates reduce the time needed for repetitive tasks.

dlearman1Author Commented:
I have followed Julian's advise and moved on to a Ajax  form using PHP MySQL and PDO.  Isn't working yet, but looking better than the original
Julian HansenCommented:
Feel free to open a question on your form if you get stuck.
dlearman1Author Commented:
Thanks Julian. I probably will run into something.
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
HTML

From novice to tech pro — start learning today.