Search code examples
phpvalidationpostmysqlisubmission

Information is not inserting in Database (What's wrong with my code?)


I am trying to make a Sign up form with validation. I add some php code to my html and css code. Everything is good. It validates if the user or email already exists. If the validation passed then the data will be save in the database but its not working. I don't know what's the problem.

Here's my code:

<?php

  if (isset($_POST['submit'])) {
    require 'connect.php';

    $username       = ($_POST['username']);
    $email          = ($_POST['email']);
    $password       = ($_POST['password']);
    $passwordconf   = ($_POST['passwordconf']);

    $errorfields    = "<p class='errormsg'>Please fill out all the fields!</p>";

    if (empty($username) || empty($email) || empty($password) || 
    empty($passwordconf))
    {
      echo "$errorfields";
    }

    $check = mysqli_query($con, "SELECT username FROM users WHERE 
    username='$username' ");

    if (mysqli_num_rows($check) >= 1) {
        echo "username already exists"."</br>". "</br>";
    }

    $erroremail     = "<p class='errormsg'>Email is not in name@domain format! </p>";
    $regex          = "/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";

    if(!preg_match($regex, $email))
    {
      echo "$erroremail";
    }

    $errorpassword  = "<p class='errormsg'>You passwords do not match!</p>";

    if ($password != $passwordconf)
    {
      echo "$errorpassword";
    }

    $check = mysqli_query($con, "SELECT email FROM users WHERE email='$email' ");

    if (mysqli_num_rows($check) >= 1) {
      echo "email already exists";
    }

   } else {

    $con = mysqli_connect('localhost' , 'root', '');

    if(!$con) {
      echo "not connected";
    }

    if (!mysqli_select_db($con, "new accounts")) {
      echo "database not selected";
    }  

    $username= (isset($_POST['username']));
    $email= (isset($_POST['email']));
    $password= (isset($_POST['password']));

    mysqli_query($con, "INSERT INTO users (username, email, password) VALUE ('$username', '$email', '$password')") or die ( "cannot insert in databse");
  }

?>

First, I wrote $username = ($_POST['username']) then it shows me error so I change it to this. it didn't show me errors but its not inserting anything in database. Can someone tell me how can I fix this problem? Thanks.


Solution

  • The short answer is:

    Your code is inserting the boolean result values from isset(), which of course is not your intent. Remove the isset() call and declare the submitted values.

    HOWEVER, there is much to fix with your code.

    This is as generous as I am willing to be for a code block with so many issues:

    <?php
    if (isset($_POST['submit']) {
        if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password']) || empty($_POST['passwordconf'])) {
            $error = "<p class='errormsg'>Please fill out all the fields!</p>";
        } elseif ($_POST['password'] !== $_POST['passwordconf']) {
            $error  = "<p class='errormsg'>You passwords do not match!</p>";
    
        } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
            $error = "<p class='errormsg'>Email is not in name@domain format!</p>";
        } else {
            require 'connect.php'; // implement object-oriented $con variable
            if ($stmt=$con->prepare("SELECT * FROM users WHERE username=?")) {
                if ($stmt->bind_param('s', $_POST['username']) && $stmt->execute() && $stmt->store_result()) {
                    if ($stmt->num_rows) {
                        $error = "<p class='errormsg'>Username already exists</p>";
                    }
                } else {
                    $error = "<p class='errormsg'>Username Check Statement Error</p>"; // $stmt->error
                }
                $stmt->close();
            } else {
                $error = "<p class='errormsg'>Username Check Prepare Error</p>"; // $con->error;
            }
            if ($stmt=$con->prepare("SELECT * FROM users WHERE email=?")) {
                if ($stmt->bind_param('s', $_POST['email']) && $stmt->execute() && $stmt->store_result()) {
                    if ($stmt->num_rows) {
                        $error = "<p class='errormsg'>Email already exists</p>";
                    }
                } else {
                    $error = "<p class='errormsg'>Email Check Statement Error</p>"; // $stmt->error
                }
                $stmt->close();
            } else {
                $error = "<p class='errormsg'>Email Check Prepare Error</p>"; // $con->error;
            }
        }
        if ($error) {
            echo $error;
        } else {
            // Perform your insert with $_POST['username'], $_POST['email'], $_POST['password'] , but DO NOT EVER, EVER, EVER store raw passwords...
            // This subject is too extensive and gathers too much scrutiny for me to dare to post any hard-fast lines of code on StackOverflow
            // Every minute that you spend researching this topic is time well spent.
            // Not learning about cryptography and password security will lead to many, many unfortunate events for you and your users.
        }
    }
    ?>
    

    So, generally speaking:

    1. Use prepared statements with placeholders for security purposes.
    2. Implement error checking so that you can debug issues quickly.
    3. Tab your code properly so that following the code logic is easy.
    4. Use an email validator rather than regex for stability.
    5. Perform simpler validation checks before more expensive ones (like query calls)
    6. Connect to your database only when necessary and re-use the same connection for all queries.
    7. A login/registration system, if done properly, is no trivial operation; research many resources and determine the best method for your php version and implement the best possible encryption and storage techniques on offer.