这是我第一次来这里,希望你能帮助我。这是我的问题:
我正忙着用oop编写一个登录脚本。
我准备了以下类:
-
数据库类
这只是一个连接/断开类 -
查询类扩展了数据库类
只有一个函数,它只需要一个查询字符串,并通过数据库得到它,并最终返回一个数组与数据。 -
登录类
这个类将获取用户登录信息并从数据库中获取用户信息。
文件夹结构:
/
/cgi-bin -> holds the database and query class
/libraries -> holds the login class
然后剩下2个文件,它们是index.php和global.php.
在我的索引中,我有这个:
require_once('global.php');
print_r($login->userCheck('test'));
这是在我的global。php中:
include('cgi-bin/database.php');
include('cgi-bin/query.php');
include('libraries/login.lib.php');
$login = new Login();
这是我的登录类
class Login extends Query{
public function Login(){
}
public function userCheck($userCredentials){
$result = $this->qString('SELECT * FROM users');
return $result;
}
}
和我的查询类
class Query extends Database{
function qString($qString){
//Start connection with database
$this->conncect();
$result = $this->db->query($qString);
// fetch associative array
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
// free result set
mysqli_free_result($result);
//Close connection with database
$this->disconnect();
//Check mysqli connection
//print_r(explode(' ', mysqli_stat($this->db)));
return $data;
}
}
和数据库类:
class Database {
//Private variables for database connection.
private $server;
private $usern;
private $userp;
private $database;
//The database object.
protected $db;
function Database(){
$dbCredentials = explode(',',file_get_contents('cgi-bin/dbcredentials.txt'));
$this->server = $dbCredentials[0];
$this->usern = $dbCredentials[1];
$this->userp = $dbCredentials[2];
$this->db = $dbCredentials[3];
}
protected function conncect(){
$this->db = mysqli_connect($this->server, $this->usern, $this->userp, $this->db);
}
protected function disconnect(){
mysqli_close($this->db);
}
}
现在当我运行这个的时候它会这样说:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:'xampp'htdocs'Login'cgi-bin'query.php on line 11
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in C:'xampp'htdocs'Login'cgi-bin'query.php on line 16
Notice: Undefined variable: data in C:'xampp'htdocs'Login'cgi-bin'query.php on line 25
为什么我得到这个错误?
编辑12-10-2011:我已经找到错误所在了。
只是为了和你分享:错误是来自数据库类的构造从未运行过。
因此,连接细节,如用户名和密码从未设置为私有变量,因此它永远无法连接。
结果查询永远不能从登录类运行。
最后很简单。
您需要阅读mysqli::query
的文档。只有当存在结果时,它才返回结果集。在错误时,它将返回布尔值false
,并且对于许多类型的查询,它将在成功时返回布尔值true
:
失败时返回FALSE。对于成功的SELECT, SHOW, DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个MySQLi_Result对象。对于其他成功的查询,mysqli_query()将返回TRUE。
您也没有检查$this->db->query(...)
的返回值。如果失败并返回false
,则盲目地将布尔值传递给mysqli_fetch_assoc
,因此出现错误消息
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
请在你的代码中添加一些基本的错误处理:
$result = $this->db->query($qString);
if ($result === false) {
// error in query
die("'$query' failed");
}
if ($result === true) {
// not a query which returns results
return true;
}
// fetch associative array
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}