使用PHP和PDO检查用户名是否存在? [英] Check username exists using PHP and PDO?
问题描述
我有一个db.php文件,其中包含以下内容:
I have a db.php file that has the following in it:
// db.php file
// creates connection to database
// DATABASE CONNECTION FUNCTION
function sql_con(){
try{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// log error to file and display friendly error to user
ExceptionErrorHandler($e);
exit;
}
}
我有一个注册页面,我想检查用户名是否已经存在,所以我事先调用了我的sql_con();
函数以连接到数据库,然后执行以下查询
I have a signup page and i want to check if username already exists, so i call my sql_con();
function beforehand to connect to database then do the below query
// connect to database
sql_con();
$stmt = $dbh->prepare("SELECT `user_login` FROM `users` WHERE `user_login` = ? LIMIT 1");
$stmt->execute(array($username));
if ( $stmt->rowCount() > 0 ) {
$error[] = 'Username already taken';
}
我对PDO还是很陌生,因此我遇到以下错误:
I'm very new to PDO and with the above i get the following errors:
注意:未定义的变量:第64行的C:\ wamp \ www \ signup.php中的dbh
Notice: Undefined variable: dbh in C:\wamp\www\signup.php on line 64
致命错误:在非对象中调用成员函数prepare() C:\ wamp \ www \ signup.php在第64行
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\signup.php on line 64
可能有些非常愚蠢的东西,而且我似乎在初学阶段就将自己与PDO混淆了.谁能告诉我我在做什么错?另外,我不确定这是否是正确的方法,因为我是PDO的新手,所以如果有更有效的方法来执行用户名查询检查,请告诉我.
Probably something very silly and I seem to confuse myself with PDO as I'm at the beginner stages. Could anyone tell me what I am doing wrong? Also I am not sure if this is the correct way as I'm new to PDO so if there's a more efficient way to do the username query check then please let me know.
推荐答案
这是因为由于范围的原因,$dbh
对象仅限于try catch
块和您的sql_con()
函数内部.
This is because the $dbh
object is limited to inside the try catch
block and your sql_con()
function due to scope.
正确的解决方案是删除try catch
块,并 在sql_con()
函数结束时返回$dbh
变量 .
The correct solution would be to remove the try catch
block, and return the $dbh
variable at the end of the sql_con()
function.
然后:
try {
$dbh = sql_con();
$stmt = $dbh->prepare("SELECT `user_login` FROM `users` WHERE `user_login` = ? LIMIT 1");
$stmt->execute(array($username));
if ( $stmt->rowCount() > 0 ) {
$error[] = 'Username already taken';
}
}
catch (PDOException $e) {
//Do stuff with $e
}
这篇关于使用PHP和PDO检查用户名是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!