What am I doing wrong ?

I'm creating a simple register-login system;
1) Registration details aren't being inserted into database
2) Having trouble logging in (I had a working registration code before but changed it because can't login, thought the register code
    was the problem. The login code is the same, can someone check if it is correct)

Database Name: reg_user
Table Name: user-reg

----Process.php----
<?PHP
  session_start();
  
  //declare variables
  $_SESSION['success'] = "";
  $username = "";
  $firstname = "";
  $lastname = "";
  $email = "";
  $resAddress = "";
  $resNumber = "";
  $mobileNumber = "";
  $birthDate = "";
  $gender = "";
  $secretQuestion = "";
  $secretAnswer = "";
  $password = "";
  $conPass = "";
  $errors = array(); 
  
  //database connection
  $conn = mysqli_connect('localhost', 'root', '', 'reg_user');
  
  /* ----REGISTRATION---- */
  if(isset($_POST['submit']) ){
    //get inputs from form
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
    $lastname = mysqli_real_escape_string($conn, $_POST['lastname']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $resAddress = mysqli_real_escape_string($conn, $_POST['res_address']);
    $resNumber = mysqli_real_escape_string($conn, $_POST['res_number']);
    $mobileNumber = mysqli_real_escape_string($conn, $_POST['mobile_number']);
    $birthDate = mysqli_real_escape_string($conn, $_POST['birthdate']);
    $gender = mysqli_real_escape_string($conn, $_POST['gender']);
    $secretQuestion = mysqli_real_escape_string($conn, $_POST['s_question']);
    $secretAnswer = mysqli_real_escape_string($conn, $_POST['s_answer']);
    $password = mysqli_real_escape_string($conn, $_POST['pword']);
    $conPass = mysqli_real_escape_string($conn, $_POST['cpword']);
    
    //If there are no problems
    $sql_query = "INSERT INTO user-reg(userName,firstName,lastName,email,resAddress,resNumber,mobileNumber,birthDate,gender,secQuestion,secAnswer,passWord) VALUES('$username', '$firstname', '$lastname', '$email', '$resAddress', '$resNumber', '$mobileNumber', '$birthDate', '$gender', '$secretQuestion', '$secretAnswer', '$password')";
    mysqli_query($conn,$sql_query);
    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now a registered user";
    header("location: login.php");
  }
  
  /*----LOGIN----*/
  if(isset($_POST['login']) ){
    $username = mysqli_real_escape_string($conn,$_POST['uname']);
    $password = mysqli_real_escape_string($conn,$_POST['p_word']);
    
    if(empty($username) ){array_push($errors, "Username is empty");}
    if(empty($password) ){array_push($errors, "Password is empty");}
    
    if(count($errors) == 0){
      $sql_query = "SELECT * FROM user-reg WHERE userName = '$username' AND passWord = '$password'";
      $result = mysqli_query($conn,$sql_query);
      
      if(mysqli_num_rows($result) == 1){
        $_SESSION['username'] = $username;
        $_SESSION['success'] = "You are logged in";
        header('location: profile.php');
      }
      else{
        array_push($errors, "Username/Password Invalid");
      }
    }
  }
?>

Open in new window


----register.php----
<?PHP
  include('process.php')
?>
<html>
  <head> 
    <link href="register CSS.css" type="text/css" rel="stylesheet">    
  </head>

<body background="images/registerbackground.jpg">
<div class="body-content">
  <div class="module">
    <h1 class="text"> Create an account</h1>
    <form method="post" action="register.php">
      <?PHP include('error.php'); ?>
      <table>
        <tr>
          <td style="padding-right:6px; height: 35px;"> Username<p class="text"> </p> <input class="textbox" type="text" name="username" value="<?PHP echo $username; ?>" required ></td>
          <td style="height: 35px"> <p class="text"> Email</p> <input class="textbox" type="email" name="email" value=" <?php echo $email; ?> " required ></td>
        </tr>
        
        <tr>
          <td style="padding-right:6px; height: 35px;"> <p class="text"> Firstname</p> <input class="textbox" type="text" name="firstname" value="<?php echo $firstname; ?>" required ></td>
	      <td style="height: 35px"> <p class="text"> Lastname</p> <input class="textbox" type="text" name="lastname" value="<?php echo $lastname; ?>" required ></td>
        </tr>
        
        <tr>
          <td style="height: 35px"> <p class="text"> Mobile Phone number</p> <input class="textbox" type="text" name="mobile_number" value="<?php echo $mobileNumber; ?>" required ></td>
          <td style="height: 35px"> <p class="text"> Home Number</p> <input class="textbox" type="text" name="res_number" value="<?php echo $resNumber; ?>"></td>
        </tr>
        
        <tr>
          <td style="padding:5px">
            <p class="text"> Gender</p>
            <select class="textbox" name="gender" value="<?php print $gender; ?>" required>
              <option selected> --Choose your gender--</option>
              <option name="male" value="male"> Male</option>
              <option name="female" value="female"> Female</option>
            </select>
          </td>
          <td>
            <p class="text"> Birthdate</p>
            <input class="textbox" type="date" name="birthdate" value="<?php echo $birthDate; ?>" required />
          </td>
        </tr>
        <tr>
          <td style="padding:5px">
            <p class="text"> Secret Question</p>
            <select class="textbox" name="s_question" value="<?php echo $secretQuestion; ?>" required>
             <option selected> --Select a secret question</option>
              <option name="q1" value="What is your first pet's name ?">What is your first pet's name ?</option>
              <option name="q2" value="What is your dream car ?"> What is your dream car ?</option>
              <option name="q3" value=" What is your favourite colour ?"> What is your favourite colour ?</option>
              <option name="q4" value="What is your mother's maiden name ?"> What is your mother's maiden name ?</option>
            </select>
          </td>
          <td style="padding:5px">
            <p class="text"> Secret Answer</p>
            <input class="textbox" type="text" name="s_answer" size="30" value="<?php echo $secretAnswer; ?>" required />
          </td>
        </tr>
      </table>
      <br>
      <p class="text"> Address</p>
      <textarea class="textbox" style="height:100px" name="res_address" cols="40" rows="10" value="<?php echo $resAddress; ?>"></textarea>
      <br><br>      
      <table>
        <tr>
          <td style="padding-right:6px">  <p class="text"> Password</p> <input class="textbox" type="password" name="pword" value="<?php echo $password; ?>" required/></td>
          
          <td> <p class="text">Confirm Password</p> <input class="textbox" type="password" name="cpword" value="<?PHP echo $conPass; ?>"/></td>
        </tr>
      </table>
      <br>
      <input class="btn" type="submit" name="submit" value="Register"/>
	</form>
  </div>
</div>
</body>
</html>

Open in new window


----login.php----
<?PHP
  include('process.php')
?>
<html>

<head>
  <link href="login CSS.css" type="text/css" rel="stylesheet">
 </head>

<body background="images/background.JPG" style="margin-top: 80px" >
  <div class="body" style="height: 576px" >
    <div class="login" style="left: 53%; top: 6%">
      <p class="text" style="font-size:xx-large; text-align:center"> Login</p>
      <p class="text" style="text-align:center"> It's easy, just enter your username and password, and you're ready to go.</p>
      
      <form method="post" action="">
        <span class="text">Username</span><br>
        <input class="textbox" type="text" placeholder="Enter username" name="uname" required >
        <br>
        <br>   
        <span class="text"> Password</span><br>
        <input class="textbox" type="password" placeholder="Enter your password" name="p_word" required>
        <br>
        <br>
        <input type="submit" class="login_btn" name="login" value="Login">   
        <br>
        <br>
      </form>
      <input type="checkbox"> <span class="text"> Remember me</span>
      </div>
      <br>
      <br>
      <p style="margin:78px 0 0 6px; letter-spacing:1px; text-shadow:0 0 10px rgba(0, 0, 0, 0.3); color:#fff"> New user ?</p>
      <a href="register.php"> <img src="images/register-link.png" alt="regiter" height="52" width="184" style="margin-left: 6px"></a>
      <p style="vertical-align:text-bottom; height: 39px;" class="forgot_password"> <a href="forgot.php"> Forgot your Username/Password ?</a></p>
    </div>
</body>

</html>

Open in new window

Izzul JazlyAsked:
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.

Chris StanyonWebDevCommented:
At a quick glance, your code looks OK (not particlarly safe and secure) but you have no error checking in place for the DB queries or the user input.

First thing I would advise is that you turn ON error reporting in your process.php script. Add this straight after your session_start call:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Open in new window


Run your scripts again and see if you get any errors or warning.

You should also add error checking around your DB stuff. Add this after your DB connection:

if (!$conn) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

Open in new window


And then again around your actual query:

if ($result = mysqli_query($conn,$sql_query)) {
   // query ran oK
   ...
} else {
   echo "Quey failed!";
}

Open in new window

You should probably do some reading up on how to secure this. You should definitely be using prepared queries here and you absolutely should encrypt the password before storing in the DB.
Dave BaldwinFixer of ProblemsCommented:
I use something like this to filter all POST data and make sure that there are acceptable values.  If you don't, it's easy to have undefined variables or indexes.
if (!isset($_POST["Email"]))  $Email = ''; else $Email = substr($_POST["Email"],0,64);

Open in new window

NerdsOfTechTechnology ScientistCommented:
Besides truncating inputs (to fewer than a certain number of characters) as Dave suggests, you should also 'sanitize' inputs to prevent attacks from malformed inputs.

There are new functions for this such as PHP's filter_var(). I use preg_replace() myself. You will want to 'filter' out characters that could form an attack. I personally filter out characters that are not [a-z][A-Z][0-9] - _ . and @, with some exceptions.

Next, it looks like you are INSERT'ing new registration info even if they are already in the database. You will want to first check if the user already exists (a SELECT query first, if not exist, then INSERT). Technically, you could do an overwrite INSERT, but this would not allow you to do the exists check properly. Therefore, I recommend opening the data table user-reg and delete the duplicate records. While you are at it, you might want to rename the table to `user` (and in code) so the engine doesn't take the table name literally as user MINUS reg or at least encapsulate it in [ ] or ` ` within queries.

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