我尝试以注册表格验证用户名字段,并检查所选用户名是否已存在于数据库中,但无法按预期工作。我不知道如何解决这个问题。这是来源
$query = "SELECT * FROM users WHERE username = :username";
$sq = $pdo->prepare($query);
$sq->execute(array(
':username' => $username
));
$res=$sq->fetch();
if (!$res) {
echo ' Database Error Occured ';
}
else { echo "username already exist in database"; }
if ($res === 0) {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->beginTransaction();
try
{
$sql = "INSERT INTO users ( username, password, email, path)
VALUES (:username, :password, :email, :path)";
$q = $pdo->prepare($sql);
$q->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':path' => $path
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("UPDATE users SET level=:user_id WHERE user_id=:user_id");
$sql->execute(array(
':user_id' => $lastInsertID
));
$pdo->commit();
}
当我点击提交按钮时发生的事情如果我输入了存在的用户名username already exist in database
但是如果我输入另一个不存在的用户名{} {}}
答案 0 :(得分:2)
if(1 < $res->rowCount()){
print('username already exist');
}
答案 1 :(得分:1)
你必须替换这个
if (!$res) {
echo ' Database Error Occured ';
}
else { echo "username already exist in database"; }
if ($res === 0) {
由此
if ($res) {
echo "username already exist in database";
}else{
答案 2 :(得分:1)
因为$sq->fetch()
返回FALSE
(它不存在)。您应该将支票更改为:
if ($res) {
echo "username already exist in database";
}
和
if ($res === FALSE) {
// Username does not exist
}