【问题标题】:How to check if username already exist using PDO?如何使用 PDO 检查用户名是否已存在?
【发布时间】:2015-08-19 00:15:10
【问题描述】:

我目前正在做一个项目,我有插入脚本。我的表称为调查,字段是 id、用户名、密码、省。用户名设置为唯一键。插入过程工作正常,没有任何重复条目,但是当我尝试插入重复条目时,总是显示此错误

SQLSTATE[23000]:违反完整性约束:1062 键“用户名”的重复条目“虚张声势”

我知道这个错误是什么意思,我的问题是,如果用户名已经存在或者不存在我怎么能弹出警报消息..

这是我的代码

class.user.php

 public function username($username){
 $stmt = $this->db->prepare("SELECT count(*) FROM tish_images WHERE username = :username");
 $stmt->execute(array($username));
 $number_of_rows = $result->fetchColumn();
 if($number_of_rows >= 1) {
     echo 'username does exist'; // or return so you get the value
 } else {
     echo 'username does not exist'; //also return?
 }
}
public function create($username,$password,$province)
{
try
{
  $stmt = $this->db->prepare("INSERT INTO tish_images(username,password,province) VALUES(:username, :password, :province)");
  $stmt->bindparam(":username",$username);
  $stmt->bindparam(":password",$password);
  $stmt->bindparam(":province",$province);
  $stmt->execute();
  return true;
}
catch(PDOException $e)
{
  echo $e->getMessage();  
  return false;
}
}

index.php

<?php
include_once 'DB.php';

$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$province = isset($_GET['province']) ? $_GET['province'] : '';

if(isset($_FILES['files'])){
$id = $_GET['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$province = $_POST['province'];

if($crud->upload($id,$FILE_NAME,$FILE_SIZE,$FILE_TYPE,$username,$password,$province))
{
    echo "<script type='text/javascript'>alert('Successfully Updated!');</script>";
}
else
{
    echo "<script type='text/javascript'>alert('Updating Failed!');</script>";
}

}
if(isset($_GET['id']))
    {
    $id = $_GET['id'];
    extract($crud->getID($id));
    }

【问题讨论】:

  • 在插入之前运行选择。如果有值提示用户选择另一个名称。如果不插入。此外,您不应该以明文形式存储密码。
  • 另一种选择是简单地捕获异常并在那里显示/触发警报。请参阅这些答案以获取示例〜stackoverflow.com/a/21869475/283366stackoverflow.com/a/21618269/283366
  • @chris85 让我更新我的代码,因为我已经尝试这样做但仍然无法正常工作
  • 你有错字是你的确切代码吗? if(username == $row['username']) 你甚至不需要这样做。如果你得到一个结果,你就知道用户名已经在数据库中了。你也执行了两次,$stmt-&gt;execute(array($username)); $stmt-&gt;execute();...并绑定了两次...$stmt-&gt;bindparam(":username", $username); $stmt-&gt;execute(array($username));
  • @kier 我的评论没有帮助吗?确定 3 个问题..

标签: php pdo


【解决方案1】:

您应该在执行查询之前运行SELECT 以查看用户名是否存在。

// count how many rows with user name exists
$checkUserStmt = $this->db->prepare("
    SELECT count(1) 
    FROM tish_images 
    WHERE username = :username
");
$checkUserStmt->execute(array(":username" => $username));

// fetch the count result
if ($checkUserStmt->fetchColumn() > 0) {
    // username already exists
} else {
    // username available 
} //if

一些笔记。

【讨论】:

  • 我到底应该把它放在哪里?因为我只是 PDO 的新手,我如何在我的 index.php 中调用它
【解决方案2】:

检查用户名或电子邮件是否已经存在。我在那里添加了电子邮件,因为这也很有用。您不希望两个用户使用相同的电子邮件地址。好吧,我认为没有必要。 :)

添加了完整的代码并且是最新的。

        $query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
        $query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
        $query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
        $query_check_user_name->execute();
        $result = $query_check_user_name->fetchAll();
        if ($result > 0) {
           echo "Someone with that username/email already exists.";
        } else {
           //Continue with proccessing the form
        }

            $query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
        $query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
        $query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
        $query_check_user_name->execute();
        $result = $query_check_user_name->fetchAll();
        if ($result > 0) {
           return true;
        } else {
           return false;
        }

【讨论】:

  • if (count($result) &gt; 0) { --- 这个检查是多余的
  • 我一直喜欢使用SELECT 1... 查询然后使用$stmt-&gt;fetchColumn()
  • @Daniel 我到底把它放在哪里?
  • Zerk 你是对的。我就这样离开了,这样才有意义。稍后我会快速将其更新为更好的形式。 @kier 听起来像是您的新用户注册。您需要做的是首先在发布的数据上运行 isset。然后是修剪。这将删除所有空格。然后检查是否为空,strlen和preg_match。之后,您要添加该代码。为了更高级,您可以有一个单独的功能来减轻服务器开销,清理/验证所有其他发布的数据,但最好保持简单以便开始。
  • @DanielBell 我如何在 index.php 中调用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 2018-09-04
  • 1970-01-01
  • 2015-06-17
  • 2016-08-08
  • 2018-07-12
  • 2019-05-24
相关资源
最近更新 更多