因此,这是一个使用PDO驱动程序将用户信息转储到数据库中的脚本。每当我用唯一的用户名运行脚本时,它就会工作并转储信息。但是,如果使用相同用户名的用户试图注册,它应该抛出一个错误。我使用$stmt->errorCode() == 23000来检查数据库中的重复,但每当我尝试注册一个用户名时,我已经注册了,我只是得到一个空白的白色屏幕。我用xDebug运行了脚本,看起来当我尝试用已经在数据库中的用户名注册时,它甚至没有击中脚本底部的if/else语句。它只是执行和抛出一个空白的屏幕。
编辑:我在数据库中的用户名字段设置为'unique'。
xDebug演练视频:http://screencast.com/t/znZfMgV2
任何想法?
// create a salt using the current timestamp
$salt = time();
// encrypt the password and salt
$password = sha1($password.$salt);
// prepare the sql statement
$sql = 'INSERT INTO users (created, username, salt, password) VALUES(now(), :username, :salt, :password)';
$stmt = $conn->prepare($sql);
// bind the parameters
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':salt', $salt, PDO::PARAM_INT);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$registerResult = "$username has been registered. You may now log in.";
} elseif ($stmt->errorCode() == 23000) {
$registerResult = "$username is already in use. Please choose another username.";
} else {
$registerResult = 'Sorry, there was a problem with the database';
}
检查错误码将不起作用,因为重复的错误将在调用execute()
时抛出异常。
你需要抓住PDOException
:
try {
// create a salt using the current timestamp
$salt = time();
// encrypt the password and salt
$password = sha1($password.$salt);
// prepare the sql statement
$sql = 'INSERT INTO users (created, username, salt, password) VALUES(now(), :username, :salt, :password)';
$stmt = $conn->prepare($sql);
// bind the parameters
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':salt', $salt, PDO::PARAM_INT);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$registerResult = "$username has been registered. You may now log in.";
}
} catch (PDOException $e) {
if ($stmt->errorCode() == 23000) {
$registerResult = "$username is already in use. Please choose another username.";
} else {
$registerResult = 'Sorry, there was a problem with the database';
}
die($e->getMessage());
}
确保你的连接设置为抛出异常:
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
PHP错误禁用?(空白页让我这么想)如果是,请尝试插入
error_reporting(-1);
ini_set('display_errors', 'On');
在你的代码中,也许空白页将开始有一些有用的错误信息。
(显然不要在服务器上使用)