我知道这是一个非常“典型”的问题,应该很容易做到,但是我无法解决为什么它不起作用的问题,将输入添加到表单中并“输入”被点击后,它直接重定向到register.php并回显来自我的connect脚本的“成功连接”。什么都没放到我的数据库中,任何我出错的指针都很棒!
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>';
}
}
?>
花了我一段时间的心思,任何帮助都将不胜感激,如果我很愚蠢,请谴责我。
答案 0 :(得分:2)
在HTML中将username="username"
更改为name="username"
,将password="password"
更改为name="password"
。
您还需要检查是否设置了_POST['enter']
而不是$_POST['register']
(感谢Patrick Q的提醒)。
正如Danielius指出的那样,在register.php中将$pdo
更改为$pdostmt
。