这个问题在这里已经有了答案:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 个回答)
6年前关闭。
config.php 文件
<?php
Class Config
{
private $_host;
private $_user;
private $_password;
private $_db;
public function __constructor()
{
$this->_host = 'localhost';
$this->_user = 'root';
$this->_password = '';
$this->_db = 'test';
}
public function connectDB()
{
$connect = new mysqli($this->_host, $this->_user, $this->_password, $this->_db);
if (!$connect) {
die('Connection Error : ' . $connect->mysql_error());
} else {
echo 'Connection Success';
}
return $connect;
}
}
?>
index.php 文件
<?php
include 'config.php';
$conn = new Config();
$conn = $conn->connectDB();
$sql = "SELECT name, matric_no FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo 'Name : ' . $row['name'] . ' - Matric No : ' . $row['matric_no'] . '<br>';
}
} ?>
显示错误:
Connection Success
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in D:\xampp\htdocs\test\index.php on line 10
有什么解决办法吗?
最佳答案
构造函数应为:
public function __construct()
public function __constructor()
根据手册:http://php.net/manual/en/language.oop5.decon.php关于构造函数和析构函数
<?php
Class Config
{
private $_host;
private $_user;
private $_password;
private $_db;
public function __construct()
{
$this->_host = 'localhost';
$this->_user = 'root';
$this->_password = '';
$this->_db = 'test';
}
public function connectDB()
{
$connect = new mysqli($this->_host, $this->_user, $this->_password, $this->_db);
if (!$connect) {
return 'Connection Error : ' . $connect->mysql_error();
} else {
return $connect;
}
}
}
?>
并在 Index.php 文件中通过 var_dump/print_r 检查连接是否成功
<?php
include 'config.php';
$conn = new Config();
$conn = $conn->connectDB();
print_r($conn); break; //Remove this line if db connxn is succesfull
$sql = "SELECT name, matric_no FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo 'Name : ' . $row['name'] . ' - Matric No : ' . $row['matric_no'] . '<br>';
}
} ?>
将执行流程牢记在心,逐点调试以找出问题所在。
关于php mysqli oops 概念连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35476770/