PDO检查行是否存在

时间:2016-04-10 09:36:10

标签: php mysql pdo

我有一个用PDO编写的注册脚本。当用户注册时,下面的代码应检查数据库中是否已存在用户名。

  • 如果是,则显示错误。
  • 如果没有,则将输入的数据插入数据库。

问题是,即使用户名存在,它仍会将输入的数据插入数据库。

这是我的数据库连接:

$db_username = "username";
$db_password = "password";

$con = new PDO("mysql:host=localhost;dbname=database", $db_username, $db_password);

这是我的注册脚本:

<?php

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

$checkusername = $stmt = $con->prepare("SELECT * FROM users WHERE username=':username'");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
if($checkusername->rowCount() > 0) {
echo "Username already exists.";
}else{

$status = 'Hello there!';
$about = 'Hello!';

$stmt = $con->prepare("INSERT INTO users (username, password, email, status, about) VALUES (:username, :password, :email, :status, :about)");

$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', md5($_POST['password']));
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':status', $status);
$stmt->bindParam(':about', $about);
$stmt->execute();

header('Location: index.php');
}
}
?>

<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="email" name="email">
<?php echo $errorusername = !empty($errorusername) ? $errorusername : ''; ?>
<?php echo $errorpassword = !empty($errorpassword) ? $errorpassword : ''; ?>
<?php echo $erroremail = !empty($erroremail) ? $erroremail : ''; ?>
<input type="submit" name="submit">
</form>

0 个答案:

没有答案