0

I've written this code for a registration page, but I am unable to get insert data into my database using PDO(or doing something incorrectly rather). Here is the registration page code:

<?php
if (empty($_POST)){

?>
 <form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label> 
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php 
}
else{
    $form = $_POST;
    $username = $form['username'];
    $password = $form['passowrd'];
    $fname = $form['fname'];
    $lname = $form['lname'];
    $email = $form['email'];
    $user = 'root';
    $pass = 'pdt1848!';

    $db = new PDO('mysql:host=localhost;dbname=phpproject', $user, $pass);


    $sql = "INSERT INTO users (username, password, fname, lname, email)VALUES(:username, :password, :fname, :lname, :email)";
    $query = $db->prepare($sql);
    $result = $query->execute(array(':username'=>$username, ':password'=>$password, 
            ':fname'=>$fname, ':lname'=>$lname, ':email'=>$email));

    if ($result){
        echo "Thanks for registering with us!";
    } else {
        echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
    };

};
?>
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • place this at the top of your script `error_reporting(E_ALL); ini_set('display_errors', 1);` what errors do you see ? – Pedro Lobito Apr 23 '14 at 22:17
  • @Fred-ii- It does not matter if `;` is there or not. Code will work in that way. Though, it is not needed there. –  Apr 23 '14 at 22:17
  • @Tuga under after – carlgoodtoseeyou Apr 23 '14 at 22:21
  • Also, when I do enter in the information and click submit, it still says "Thanks for registering with us!" as if $result occurred. – carlgoodtoseeyou Apr 23 '14 at 22:22
  • 1
    Add `$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` right after `$db = new ...` and keep there the `error_reporting` which @Tuga suggested and tell us if anything showed up. –  Apr 23 '14 at 22:24
  • @user3566526 what Yoda says ;p – Lawrence Cherone Apr 23 '14 at 22:24
  • Nevermind my previous comment. This was due to my file not being saved as register.php it is now showing the error message like it should. Thanks to your advice @Tuga I figured it out. I mispelled 'password' as 'passowrd' -_- thanks for the assistance guys! No doubt I'll be back. Also thanks for the tip Yoda – carlgoodtoseeyou Apr 23 '14 at 22:34

3 Answers3

2

The error is right here, passowrd

$password = $form['passowrd'];

A mere typo.

change it to:

$password = $form['password'];

when one fails, the whole query fails.

Had you error reporting in your code, it would've picked it up right away.

Ways that you can use in the future are a try & catch method, such as:

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

as well as

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

Links that you can consult for further reading:

PDO

MySQL

(more)


Passwords

I also noticed that you are storing passwords in plain text. This is not recommended.

Use one of the following:

Other links:

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

Well I do something like this,

$user = 'your username';
$pass = 'your pass';
$db = new PDO( 'mysql:host=localhost;dbname=your_data_base_name', $user, $pass );
/*Grab Post*/
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$first_name = $form[ 'first_name' ];
$surname = $form[ 'surname' ];
$address = $form[ 'address' ];
$email = $form[ 'email' ];
// Sql
$sql = "INSERT INTO users ( username, password, first_name, surname, address, email )      VALUES ( :username, :password, :first_name, :surname, :address, :email )";

$result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':first_name'=>$first_name, ':surname'=>$surname, ':address'=>$address, ':email'=>$email ) );

if ( $result ){
   echo "Thank you. You have been registered";
} else {
   echo "Sorry, there has been a problem inserting your details.";
}

In addition I always, enable my error reporting as Tuga suggested. It never fails me.

Nepal12
  • 583
  • 1
  • 12
  • 29
0

apart from the typo in the passowrd you should enable exceptions for PDO and use a try and catch statement to catch the exception. Also some other little changes, like structuring the PHP first and removing the odd re-assign of the POST superglobal.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    $result = "Thanks for registering with us!";
    try{
        $db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);


        $sql = "INSERT INTO users (username,   password,  fname,  lname,  email)
                            VALUES(:username, :password, :fname, :lname, :email)";
        $query = $db->prepare($sql);
        $query->execute(array(':username'=>$_POST['username'],
                              ':password'=>$_POST['password'],
                              ':fname'=>$_POST['fname'],
                              ':lname'=>$_POST['lname'],
                              ':email'=>$_POST['email']));
    }catch(PDOException $e){
        $result = 'Sorry, an error occurred while editing the database. Contact the guy who built this garbage.';
        //or use $e->getMessage(); for the real error
    }

    echo $result;

}
else{ ?>
<form name="registration" action="register.php" method="POST">
    <label for "username">Username: </label>
    <input type="text" name="username"/><br />
    <label for "password">Password: </label>
    <input type="password" name="password"/><br />
    <label for "fname">First Name: </label>
    <input type="text" name="fname"/><br />
    <label for "lname">Last name: </label> 
    <input type="text" name="lname"/><br />
    <label for "email">Email: </label>
    <input type="text" name="email"/><br />
    <button type="submit">Submit</button>
</form>
<?php } ?>

Also its a very bad idea to store plain-text passwords in your db. ~ Read: Best way to store password in database.

Edit,

Added some validation of your inputs to help you get started, hope it helps. not tested.

<?php
try{
    $db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch(PDOException $e){
    die('Sorry, an error occurred while editing the database. Contact the guy who built this garbage.');
    //or use $e->getMessage(); for the real error
}


if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    //create empty error array - to fill with errors if any
    $error = array();

    //validate username
    if(empty($_POST['username'])){
        $error['username'] = 'Enter a username';
    }elseif(strlen($_POST['username']) <= 2){
        $error['username'] = 'Username too short > 2 chars';
    }else{
        //check for existing user
        $sql = "SELECT 1 
                FROM `users` 
                WHERE username = :username";

        $query = $db->prepare($sql);
        $query->execute(array(':username' => $_POST['username']));

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        if(!empty($result)){
            $error['username'] = 'User already exists'; 
        }
    }

    //validate pass
    if(empty($_POST['password'])){
        $error['password'] = 'Please enter password';
    }elseif(strlen($_POST['password']) < 6){
        $error['password'] = 'Password too short, password should be 6 chars or longer';
    }

    //validate fname
    if(empty($_POST['fname'])){
        $error['fname'] = 'Please enter your first name';
    }

    //validate fname
    if(empty($_POST['lname'])){
        $error['lname'] = 'Please enter your last name';
    }


    //validate email
    if(empty($_POST['email'])){
        $error['email'] = 'Please enter your email';
    }else{
        if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $error['email'] = 'Please enter valid email';   
        }
    }

    //no errors detected so insert
    if(empty($error)){
        $sql = "INSERT INTO users (username,   password,  fname,  lname,  email)
                            VALUES(:username, :password, :fname, :lname, :email)";
        $query = $db->prepare($sql);
        $query->execute(array(':username'=>$_POST['username'],
                             ':password'=>$_POST['password'],
                             ':fname'=>$_POST['fname'],
                             ':lname'=>$_POST['lname'],
                             ':email'=>$_POST['email']));

        $result = 'Thanks for registering with us! <a href="login.php">Click here to login</a>';
    }else{
        $result = 'Please correct the errors';
    }

}?>

<?php echo isset($result) ? $result : null;?>

<form name="registration" action="register.php" method="POST">
    <label for "username">Username: <?php echo isset($error['username']) ? $error['username'] : null;?></label>
    <input type="text" name="username"/><br />
    <label for "password">Password: <?php echo isset($error['password']) ? $error['password'] : null;?></label>
    <input type="password" name="password"/><br />
    <label for "fname">First Name: <?php echo isset($error['fname']) ? $error['fname'] : null;?></label>
    <input type="text" name="fname"/><br />
    <label for "lname">Last name: <?php echo isset($error['lname']) ? $error['lname'] : null;?></label> 
    <input type="text" name="lname"/><br />
    <label for "email">Email: <?php echo isset($error['email']) ? $error['email'] : null;?></label>
    <input type="text" name="email"/><br />
    <button type="submit">Submit</button>
</form>
Community
  • 1
  • 1
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • would you mind explaining that first line? "if ($_SERVER['REQUEST_METHOD'] == 'POST'){" – carlgoodtoseeyou Apr 24 '14 at 00:38
  • @user3566526 its the proper way to check that the request method is POST, From the [manual](http://www.php.net/manual/en/reserved.variables.server.php) 'REQUEST_METHOD' Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'. – Lawrence Cherone Apr 24 '14 at 00:41
  • you might want to add validation onto all of your POST inputs, in-case a user or bot just submits the form with blank values, causing you to get lots of empty rows inserted, also check for existing users before inserting – Lawrence Cherone Apr 24 '14 at 00:45
  • @carlgoodtoseeyou added an edited version with some validation, to help you get started. your welcome – Lawrence Cherone Apr 24 '14 at 01:11
  • I'm attempting to use phpass; I'm just a little unsure how to go about it.. I have the code, I just don't know where, or rather how to implement it. $password =$_POST['password']; $hash_obj = new PasswordHash(8, false); $hash = $hash_obj->HashPassword($password); $db_obj->insert_password($hash). $db_obj->insert_password($hash)." – carlgoodtoseeyou Apr 24 '14 at 01:15
  • Ive never used it, generally you have a combination of 3 hashs to make the final hash thats not stored, a server hash key which is known only to the server, a user salt which is stored along with the users hash in the database, and the users hash, all 3 keys are salted together to make the final hash which is then checked. basically you need to hash the users password which is salted with an algo like sha512 or such, something strong not md5 or sha1. – Lawrence Cherone Apr 24 '14 at 01:23
  • Check out this login class, it pretty much explains in code what i mean. http://stackoverflow.com/questions/11515739/script-wont-log-in/11515866#11515866 – Lawrence Cherone Apr 24 '14 at 01:27
  • Thanks for all your advice, I'm still trying to get a grip on try catch and PDO in general. – carlgoodtoseeyou Apr 24 '14 at 03:52