我正在为我的应用程序编写一个小型登录类,但是,我认为我的查询很糟糕,因为当我调用mysql_fetch_assoc()
查询结果时,我收到此错误:
警告:mysql_fetch_assoc() 期望参数 1 是资源,给定的布尔值
我熟悉它的mysql_fetch_assoc()
工作原理,但我猜对的调用mysql_query()
返回 false,这显然是一个布尔值,会产生错误。
这是查询:
$loginsql = 'SELECT userid, username, password FROM users WHERE username=\'. $username .\' AND password=\'. $password .\'';
注意:我意识到 PHP 中设置的“mysql_”函数自 5.5 起已弃用,但我使用的是 5.3.8,只是在练习。稍后我将使用 PDO 重构应用程序。
类.php
<?php
class connectToDb {
function dbConnect($config) {
$connection = mysql_connect($config['host'], $config['dbuser'], $config['dbpass']);
if ($connection) {
mysql_select_db($config['db'], $connection);
} else {
echo "Could not connect to database!";
}
}
}
class registerAccount {
function doRegister($regusername, $regpassword, $regemail) {
$regsql = "INSERT INTO users (username, password, email) VALUES ('$regusername', '$regpassword', '$regemail')";
if (mysql_query($regsql)) {
echo "Successfully registered!";
} else {
echo "Problem with registration!";
}
}
}
class loginAccount {
function doLogin($username, $password) {
mysql_real_escape_string($username);
mysql_real_escape_string($password);
hash('sha256', $password);
$loginsql = 'SELECT userid, username, password FROM users WHERE username=\'. $username .\' AND password=\'. $password .\'';
$result = mysql_query($loginsql) or die(mysql_error());
$loginrow = mysql_fetch_assoc($result);
if ($loginrow) {
$_SESSION['username'] = $loginrow['username'];
$_SESSION['userid'] = $loginrow['userid'];
} else {
echo "Incorrect username and/or password!";
}
}
}