我正在尝试在PHP中创建用户登录/创建脚本,并且想知道在创建用户时检查用户名是否存在的最佳方法。目前,我有以下代码:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
我不确定这是做这件事的最佳逻辑。我正在考虑添加一个布尔变量来执行类似的操作(在if语句之后):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
但这似乎效率不高 - 是否有更有效的方法来做到这一点?对不起,如果这有一个基本的解决方案 - 我是一个相对较新的PHP程序员。
答案 0 :(得分:7)
使用WHERE
子句仅获取具有给定用户名的行:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
然后检查查询是否导致选择MySQLi_Result::num_rows
的任何行(0行或0行):
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
答案 1 :(得分:2)
这基本上涉及在将成员插入数据库之前,通常在验证期间进行查询。
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
上面的示例使用PHP的PDO,因此请更改语法以使用您使用的任何数据库抽象。