简体   繁体   中英

PHP PDO registration not working?

I know this is a very 'typical' question, it should be something so easy to do but I can't wrap my head around why it isn't working?, Once input is added to the form and 'enter' is hit, it simply redirects to register.php and echos 'connected succesfully' which is from my connect script. Nothing gets put into my database at all, any pointers where I'm going wrong would be great!

HTML

    <form method "POST" id="regform" action="register.php">
    <input type="text" username="username" placeholder="Please enter your 
    email"/>
    <input type="text" password="password" placeholder="Please create a 
    password"/>
    <input type="submit" value="enter"/>
    </form>

Connect.php

<?php

$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";


try{
$pdostmt = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, 
$dbpassword);
 $pdostmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 echo "connected succesfully";
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>

register.php

<?php
// Starting the session and connecting to the DB
session_start();
require_once'connect.php';

if(isset($_POST['register'])){


$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;

$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':username', $username);


$stmt->execute();


$row = $stmt->fetch(PDO::FETCH_ASSOC);


if($row['num'] > 0){
    die('That username already exists!');
}

$sql = "INSERT INTO users (username, password) VALUES (:username, 
:password)";
$stmt = $pdo->prepare($sql);

$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);

$result = $stmt->execute();

if($result){
    echo 'Thank you for registering with our website.';
            header("Location: index.php");
 }
    else {
        echo '<b> There has been an error please contact support </b>';
    }

}

?>

Been racking my brain over this for a while, any help would be appreciated and if i'm being stupid berate me.

Change username="username" to name="username" and password="password" to name="password" in your HTML.

You also need to check to see if _POST['enter'] is set instead of $_POST['register'] (thanks for the reminder Patrick Q).

And as Danielius points out, change $pdo to $pdostmt in register.php.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM