【发布时间】: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/283366和stackoverflow.com/a/21618269/283366
-
@chris85 让我更新我的代码,因为我已经尝试这样做但仍然无法正常工作
-
你有错字是你的确切代码吗?
if(username == $row['username'])你甚至不需要这样做。如果你得到一个结果,你就知道用户名已经在数据库中了。你也执行了两次,$stmt->execute(array($username)); $stmt->execute();...并绑定了两次...$stmt->bindparam(":username", $username); $stmt->execute(array($username)); -
@kier 我的评论没有帮助吗?确定 3 个问题..