我正在尝试下面的代码来检查数据库中是否存在用户,并根据输出返回结果。但我得到了"致命错误:方法名称必须是…………..行中的字符串"。那么,代码中出了什么问题。有什么建议吗?
<?php
$user_email="somthing@gmail.com";
try
{
/*** connect to database ***/
/*** mysql hostname ***/
$mysql_hostname = '127.0.0.1';
/*** mysql username ***/
$mysql_username = 'root';
/*** mysql password ***/
$mysql_password = '';
/*** database name ***/
$mysql_dbname = 'something';
/*** select the users name from the database ***/
$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($this->$dbh()) {
// check if username or email already exists
$query_check_user_email = $this->$dbh->prepare('SELECT user_email FROM users WHERE user_email=:user_email');
$query_check_user_email->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_email->execute();
$result = $query_check_user_email->fetchAll();
// if username or/and email find in the database
// TODO: this is really awful!
if (count($result) > 0) {
echo "exists!";
}
} else {
echo "non existant";
}
?>
有什么建议吗?
第一个:
$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
这将是php块/文件/任何内容范围内的一个变量。您实际上并没有将其设置为成员,因为您不在类中。
第二:$this->$dbh()
。
您不在类成员方法的作用域中。您的代码所在的位置没有$this
。
尝试简单使用:$dbh
必须使用$dbh
而不是$this->dbh
:
if ($dbh) {
// check if username or email already exists
$query_check_user_email = $dbh->prepare('SELECT user_email FROM users
WHERE user_email=:user_email');
$query_check_user_email->bindValue(':user_email',
$user_email, PDO::PARAM_STR);
$query_check_user_email->execute();
$result = $query_check_user_email->fetchAll();
// if username or/and email find in the database
// TODO: this is really awful!
if (count($result) > 0) {
echo "exists!";
}
} else {
echo "non existant";
}
?>
也许这有助于
$stmt = $dbh->prepare("SELECT * FROM user WHERE user_email = :email;");
$stmt->bindParam(":email", $email);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_BOTH);
顺便说一句,我更喜欢调用表user而不是users。