Form doesn't add User to Database

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 1645 Views - Last Post: 30 April 2018 - 05:42 AM Rate Topic: ***** 1 Votes

#1 Heathersmithx   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 68
  • Joined: 07-November 16

Form doesn't add User to Database

Posted 26 April 2018 - 08:17 PM

I'm just adding a new user to my database. My database has a table called User.
I'm trying to add the username and the hashed password to my table.

When I submit the form, it echos that the passwords matched, so it at least gets that far.
I'm not sure why it's not telling me that the user was successfully added, or what
error is occuring.

No one gets added to the table, and nothing happens.

I also want to hide the form when the user clicks submit. I put the javascript in there, and on the submit button I put
onclick do the function to hide it the script is in the same page for that.
But nothing gets hidden. :(

I need some help here. It's finals, and I have to get moving on to the actual login page for users who exist!

Here it all is.
It includes the navBar file, which is just the html for the navBar up top, and the host connection, which is working properly.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>ACME company</title>
        <link rel="stylesheet" type="text/css" href="acme.css">
      
        <script>

            var submitButton = document.getElementById("submitButton");
            var form = document.getElementById("newUserForm");
            function hide{
            form.style.display = "none";
            }
            function back{
            window.history.back();
            }

        </script>
    </head>
    <body>
        <?php
        include 'navBar.php';
        include 'hostConnection.php';
        ?>
        <!--NEW USER FORM-->
        <div class="form-group" id="newUserForm">
            <form class="form-horizontal" action="" method="post" id="newUserForm">
                <!--USERNAME-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="user">Username</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" id="user" placeholder="New Username" name="username" value="<?php $username;?>">
                    </div>
                </div>
                <!--PASSWORD-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="pwd">Password:</label>
                    <div class="col-sm-8"> 
                        <input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
                    </div>
                </div>
                <!--CONFIRM PASSWORD-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="pwd">Confirm Password:</label>
                    <div class="col-sm-8"> 
                        <input type="password" class="form-control" id="password" placeholder="Confirm Password" name="confirmPass">
                    </div>
                </div>
                <!--SUBMIT BUTTON-->
                <div class="form-group"> 
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-default" name="submitButton" onsubmit="hide()">Submit</button>
                    </div>
                </div>
            </form>
        </div>

        <?php
        //IF THE SUBMIT BUTTON WAS PRESSED = TRUE
        if (isset($_POST["submitButton"])) {

            $username = mysqli_real_escape_string($con, $_POST['username']);
            $password = mysqli_real_escape_string($con, $_POST['password']);
            $passwordConfirm = mysqli_real_escape_string($con, $_POST['confirmPass']);
            //HASHING ALGORITHM
            $algo = "Tiger160";
            $hashedPass;
            //CHECK IF USER ALREADY EXISTS 
            $result = mysqli_query($con, "SELECT * FROM User WHERE Username='$username'");
            $row = mysqli_affected_rows($query);
            //SHOULD RETURN ZERO ROWS IF USER DOESN'T EXIST
            //PROVIDE A TRY AGAIN BUTTON AND A LOGIN BUTTON
            if ($row > 0) {
                echo("<h2>" . $username . " already exists.</h2>");
                echo("<button action='login.php' id='login'>Login</button>");
                echo("<button action='' onclick='back()' id='tryAgain'>Try Again</button>");
            }
            //MAKE SURE PASSWORD & CONFIRM PASSWORD MATCH. 
            if ($password === $passwordConfirm) {
                echo "passwords matched";
                //HASH THE PASSWORD USING THE ALGORITHM
                $hashedPass = password_hash($password, $algo);
                $sql = "INSERT INTO User (Username, Password) VALUES ('$username', '$hashedPass')";
                //INSERT THE NEW USER AND HASHED PASSWORD INTO THE  DATABASE;
                if ($con->query($sql) === TRUE) {
                    echo "Thank you for registering, $username!";
                } else {
                    echo "There was an Error: " . $sql . "<br>" . $con->error;
                }
            }
        }
        ?>
    </body>
</html>



Is This A Good Question/Topic? 0
  • +

Replies To: Form doesn't add User to Database

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5315
  • View blog
  • Posts: 14,185
  • Joined: 18-April 07

Re: Form doesn't add User to Database

Posted 27 April 2018 - 07:15 AM

Is there a particular reason you are changing query styles? At the top you go mysqli_query($con, query) and then you switch to $con->query. Try using mysqli_query($con,query) again and see if that helps. I am not sure if you even have a $con object created correctly. Are you sure you are looking at the right database table and that perhaps it is not a mistake in how you are looking at the database?
Was This Post Helpful? 1
  • +
  • -

#3 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2688
  • View blog
  • Posts: 10,767
  • Joined: 03-December 12

Re: Form doesn't add User to Database

Posted 27 April 2018 - 07:25 AM

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


First and foremost, make sure you can see the errors that are occurring.
Was This Post Helpful? 1
  • +
  • -

#4 no2pencil   User is offline

  • Professor Snuggly Pants
  • member icon

Reputation: 6715
  • View blog
  • Posts: 31,112
  • Joined: 10-May 07

Re: Form doesn't add User to Database

Posted 27 April 2018 - 07:38 AM

I would either print the value of this variable into a log file, or to the screen :

$sql = "INSERT INTO User (Username, Password) VALUES ('$username', '$hashedPass')";


If all values within $sql are as expected, I would then run it on the mysql command line.
Was This Post Helpful? 0
  • +
  • -

#5 Heathersmithx   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 68
  • Joined: 07-November 16

Re: Form doesn't add User to Database

Posted 27 April 2018 - 09:33 AM

Here is my mysqli object host connection code.
<?php

$user = 'root';
$password = 'dbpass';
$db = 'Commerce';
$host = 'localhost';
$table = 'User';

$con = new mysqli($host,$user,$password,$db);
// Check connection
if ($mysqli->connect_errno)
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }



Was This Post Helpful? 0
  • +
  • -

#6 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2688
  • View blog
  • Posts: 10,767
  • Joined: 03-December 12

Re: Form doesn't add User to Database

Posted 27 April 2018 - 09:42 AM

Then you are using the OOP style. Best to stick with one or the other.
Was This Post Helpful? 1
  • +
  • -

#7 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2688
  • View blog
  • Posts: 10,767
  • Joined: 03-December 12

Re: Form doesn't add User to Database

Posted 27 April 2018 - 09:57 AM

First, let's do some reordering. You want the page to process first, not last.

<?php
        //IF THE SUBMIT BUTTON WAS PRESSED = TRUE
        if (isset($_POST["submitButton"])) {

            $username = mysqli_real_escape_string($con, $_POST['username']);
            $password = mysqli_real_escape_string($con, $_POST['password']);
            $passwordConfirm = mysqli_real_escape_string($con, $_POST['confirmPass']);
            //HASHING ALGORITHM
            $algo = "Tiger160";
            $hashedPass;
            //CHECK IF USER ALREADY EXISTS 
            $result = mysqli_query($con, "SELECT * FROM User WHERE Username='$username'");
            $row = mysqli_affected_rows($query);
            //SHOULD RETURN ZERO ROWS IF USER DOESN'T EXIST
            //PROVIDE A TRY AGAIN BUTTON AND A LOGIN BUTTON
            if ($row > 0) {
                echo("<h2>" . $username . " already exists.</h2>");
                echo("<button action='login.php' id='login'>Login</button>");
                echo("<button action='' onclick='back()' id='tryAgain'>Try Again</button>");
            }
            //MAKE SURE PASSWORD & CONFIRM PASSWORD MATCH. 
            if ($password === $passwordConfirm) {
                echo "passwords matched";
                //HASH THE PASSWORD USING THE ALGORITHM
                $hashedPass = password_hash($password, $algo);
                $sql = "INSERT INTO User (Username, Password) VALUES ('$username', '$hashedPass')";
                //INSERT THE NEW USER AND HASHED PASSWORD INTO THE  DATABASE;
                if ($con->query($sql) === TRUE) {
                    echo "Thank you for registering, $username!";
                } else {
                    echo "There was an Error: " . $sql . "<br>" . $con->error;
                }
            }
        }
        ?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>ACME company</title>
        <link rel="stylesheet" type="text/css" href="acme.css">
      
        <script>

            var submitButton = document.getElementById("submitButton");
            var form = document.getElementById("newUserForm");
            function hide{
            form.style.display = "none";
            }
            function back{
            window.history.back();
            }

        </script>
    </head>
    <body>
        <?php
        include 'navBar.php';
        include 'hostConnection.php';
        ?>
        <!--NEW USER FORM-->
        <div class="form-group" id="newUserForm">
            <form class="form-horizontal" action="" method="post" id="newUserForm">
                <!--USERNAME-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="user">Username</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" id="user" placeholder="New Username" name="username" value="<?php $username;?>">
                    </div>
                </div>
                <!--PASSWORD-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="pwd">Password:</label>
                    <div class="col-sm-8"> 
                        <input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
                    </div>
                </div>
                <!--CONFIRM PASSWORD-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="pwd">Confirm Password:</label>
                    <div class="col-sm-8"> 
                        <input type="password" class="form-control" id="password" placeholder="Confirm Password" name="confirmPass">
                    </div>
                </div>
                <!--SUBMIT BUTTON-->
                <div class="form-group"> 
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-default" name="submitButton" onsubmit="hide()">Submit</button>
                    </div>
                </div>
            </form>
        </div>


    </body>
</html>



Next, you aren't submitting the form via AJAX, so there is no need to hide the form, it will reload the page.

Also, use prepared statements and drop the real_escape_string:
//HASHING ALGORITHM
$algo = "Tiger160";
$hashedPass; // what is the purpose of this variable?
//CHECK IF USER ALREADY EXISTS 
$stmt = $con->prepare("SELECT * FROM User WHERE Username=?");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
            
$result = $stmt->fetch_all(MYSQLI_ASSOC);

Was This Post Helpful? 2
  • +
  • -

#8 Heathersmithx   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 68
  • Joined: 07-November 16

Re: Form doesn't add User to Database

Posted 27 April 2018 - 10:57 AM

I'm trying to hash the password before I put it in the database. I've never done it before. My teacher has been having problems with his database all semester, so in class we have been helping each other, and I'm mostly learning everything online by myself. So in class we didn't go over how to hash a password at all. He just said, hash the password in the final. So I'm really not sure if I'm doing it right at all.

I'm re-organizing the code now like you said to do, I'm going to change the $con to mysqli_connect instead to see if that works any differently. So I can't use those two types interchangeably then? That's good to know.

We kind of went over prepared statements... But can you explain to me why I would do that instead of using real_escape_string? I can look that one up, you don't have to explain. I'm just trying to get this all straight. I have to have my Ecommerce site working by today because I have to study for Data structures and algorithms the rest of the weekend or I'll probably fail miserably in life!

So I'm sorry for my ignorance I'm still trying to learn.
Was This Post Helpful? 0
  • +
  • -

#9 Heathersmithx   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 68
  • Joined: 07-November 16

Re: Form doesn't add User to Database

Posted 27 April 2018 - 11:07 AM

This is my new hostConnection.php doing it the other way. Is there a better way to tell if it's for sure connected?

<?php

$user = 'root';
$password = 'dbpass';
$db = 'Commerce';
$host = 'localhost';
$table = 'User';

$con = mysqli_connect($host,$user,$password,$db);

// Check connection
if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  else{
   echo"connected!";
  }


Was This Post Helpful? 0
  • +
  • -

#10 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2187
  • View blog
  • Posts: 6,616
  • Joined: 15-January 14

Re: Form doesn't add User to Database

Posted 27 April 2018 - 11:17 AM

Yes, there will be an error message if it's not connected and you try to do things with it. But make sure you're seeing all error messages, add that code from astonecipher to the top of your PHP code or the top of your include file, that code to set the error reporting options should run before anything else. Next, check the value of $con after you tried to connect, it will be false if it didn't connect and you can print the error message from the database. The manual has examples for checking for a connection error:

http://php.net/manua...i.construct.php
Was This Post Helpful? 1
  • +
  • -

#11 Heathersmithx   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 68
  • Joined: 07-November 16

Re: Form doesn't add User to Database

Posted 27 April 2018 - 12:10 PM

Okay, Here is my updated hostConnection.php. I'll make sure this runs first.
My question is about these init_set things... Do I keep this code in here all the time,
or do I only use this code when I'm debugging and writing the site?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$user = 'root';
$password = 'dbpass';
$db = 'Commerce';
$host = 'localhost';
$table = 'User';

$con = mysqli_connect($host,$user,$password,$db);

// Check connection
if (!$con)
  {
   die("<h1>UNABLE TO CONNECT: </h1>\n" 
     . "<h3>ERROR: " . mysqli_connect_errno() 
     . "<h3>ERROR MESSAGE:<h3>" . mysqli_connect_error());
  }
  else{
      echo"<h1>connected!</h1>";
  }



Here is my very first attempt at prepared statements
I'm not sure if it's correct.
There are some questions in the comments.

 //CHECK IF USER ALREADY EXISTS 
//Do I need to have single quotes around the question mark?????

            $sql = "SELECT * FROM User WHERE Username= ?"; 
            $stmt = mysqli_prepare($con, $sql);
//when I am binding multiple parameters would it look like
// mysqli_stmt_bind_param($stmt, "ss", $username $password); 
//comma between username and password???? or no comma????
             mysqli_stmt_bind_param($stmt, "s", $username);?????

             mysqli_stmt_execute($stmt);

            $row = mysqli_stmt_affected_rows($stmt);

           //IF IT RETURNS ANY ROWS THE USER ALREADY EXISTS.
            if ($row > 0) 
            {
                echo("<h2>" . $username . " already exists.</h2>");
                echo("<button action='login.php' id='login'>Login</button>");
                echo("<button action='' onclick='back()' id='tryAgain'>Try 
                         Again</button>");
            }
            else  
//IS THIS THE CORRECT WAY TO RETURN AN ERROR FROM A PREPARED STATEMENT????? 
            {
                echo "Errormessage: %s\n", mysqli_error($con);
            }


Was This Post Helpful? 0
  • +
  • -

#12 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2688
  • View blog
  • Posts: 10,767
  • Joined: 03-December 12

Re: Form doesn't add User to Database

Posted 27 April 2018 - 12:58 PM

Quote

So in class we didn't go over how to hash a password at all. He just said, hash the password in the final. So I'm really not sure if I'm doing it right at all.


The standard is to use password_hash

$password = 'my_Password123';
$hashed = password_hash($password, 1); // means the system default algo. It's what you want to use


NOW, password_hash is interesting in that it doesn't dulpicate the hash. It uses a random salt and verifies it so you can't compare two and expect the same result. So, they have password_verify that does that for you.

if(password_verify($password, $hashed))
    // password matches



Quote

My question is about these init_set things... Do I keep this code in here all the time,
or do I only use this code when I'm debugging and writing the site?

Only when you are debugging. You don't want users to have the messages the server gives back when there are errors. You would log the errors somehow to deal with later or see what happened.

Quote

//Do I need to have single quotes around the question mark?????

Nope, handled for you.

Quote

//when I am binding multiple parameters would it look like
// mysqli_stmt_bind_param($stmt, "ss", $username $password);


mysqli_stmt_bind_param($stmt, "ss", $username, $password);

Was This Post Helpful? 1
  • +
  • -

#13 Heathersmithx   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 68
  • Joined: 07-November 16

Re: Form doesn't add User to Database

Posted 27 April 2018 - 02:03 PM

This is all of the changes I think you've asked me to do. Now I'm getting an error message that I'm assuming must come from that init_set error stuff. that says:

Errormessage: %s Fatal error: Call to undefined function password_hash() in /var/www/html/ECommerce/newUser.php on line 33


Can I just say how much I love you guys for helping me right now! I really really appreciate it. I would bake you cookies if I could bake!

<?php
include 'navBar.php';
include 'hostConnection.php';
//IF THE SUBMIT BUTTON WAS PRESSED = TRUE
if (isset($_POST['submitButton'])) {

    $username = ($_POST["username"]);
    $password = ($_POST["password"]);
    $passwordConfirm = ($_POST["confirmPass"]);
    $algo = "Tiger160";
   
    //CHECK IF USER ALREADY EXISTS 
    $sql = "SELECT * FROM User WHERE Username= ?";
    $stmt = mysqli_prepare($con, $sql);
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    $row = mysqli_stmt_affected_rows($stmt);
    //SHOULD RETURN ZERO ROWS IF USER DOESN'T EXIST
    //PROVIDE A TRY AGAIN BUTTON AND A LOGIN BUTTON
    if ($row > 0) {
        echo("<h2>" . $username . " already exists.</h2>");
        echo("<button action='login.php' id='login'>Login</button>");
        //echo("<button action='' onclick='back()' id='tryAgain'>Try Again</button>");
    } else {
        echo "Errormessage: %s\n", mysqli_error($con);
    }

    //MAKE SURE PASSWORD & CONFIRM PASSWORD MATCH. 
    
    if ($password == $passwordConfirm) {
        //HASH THE PASSWORD USING THE ALGORITHM
        $hashedPass = password_hash($password, 1); //this is line 33 on my file
        if(!$hashedPass){
           echo"The password was not hashed";
        }
        
        $sql = "INSERT INTO User (Username, Password) VALUES (?,?)";
        $stmt = mysqli_prepare($con, $sql);
        mysqli_stmt_bind_param($stmt, "ss", $username,$hashedPass);
        $result = mysqli_stmt_execute($stmt);
        
        //INSERT THE NEW USER AND HASHED PASSWORD INTO THE  DATABASE;
        if ($result) {
            echo "<h1>Thank you for registering, $username!</h1>";
        } else {
            echo "<h1 style='color: red'>There was an Error: </h1>\n" ."<h3>" . mysqli_error($con) . "</h3>";
        }
    }else{
        echo"<h2>The passwords you entered don't match. Please try again.</h2>";
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>ACME company</title>
        <link rel="stylesheet" type="text/css" href="acme.css">
        <script>
            function back() {
                window.history.back();
            }
        </script>
    </head>
    <body>
        <!--NEW USER FORM-->
        <div class="form-group" id="newUserForm">
            <form class="form-horizontal" action="" method="post" id="newUserForm">
                <!--USERNAME-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="user">Username</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" id="user" placeholder="New Username" name="username">
                    </div>
                </div>
                <!--PASSWORD-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="pwd">Password:</label>
                    <div class="col-sm-8"> 
                        <input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
                    </div>
                </div>
                <!--CONFIRM PASSWORD-->
                <div class="form-group">
                    <label class="control-label col-sm-2" for="pwd">Confirm Password:</label>
                    <div class="col-sm-8"> 
                        <input type="password" class="form-control" id="password" placeholder="Confirm Password" name="confirmPass">
                    </div>
                </div>
                <!--SUBMIT BUTTON-->
                <div class="form-group"> 
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-default" name="submitButton">Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>


Was This Post Helpful? 0
  • +
  • -

#14 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2688
  • View blog
  • Posts: 10,767
  • Joined: 03-December 12

Re: Form doesn't add User to Database

Posted 27 April 2018 - 02:25 PM

https://secure.php.n...ssword-hash.php


So, you have an OLD version of php...
Was This Post Helpful? 1
  • +
  • -

#15 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2187
  • View blog
  • Posts: 6,616
  • Joined: 15-January 14

Re: Form doesn't add User to Database

Posted 27 April 2018 - 02:57 PM

Also, just to point out, you were still getting that fatal error, you just weren't seeing the error message. That's why your code was failing before, when it tried to run that function it just had a fatal error and quit, but it didn't print the error message because of the PHP settings.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2