这是我得到的错误:
mysqli_query() 期望参数 1 是 mysqli,对象在第 11 行的 E:''wamp''www''mm''classes''db_class.php 中给出
我有三个文件
- 配置.php
-
db_class.php - 索引.php
配置.php
error_reporting(E_ALL);
define('HOST','localhost');
define('USER','root');
define('PASSWORD','');
define('DATABASE','mm');
class con {
function __construct(){
$con=mysqli_connect(HOST, USER, PASSWORD, DATABASE);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
}
db_class.php
<?php
include 'config.php';
class db {
private $con;
function __construct($con) {
$this->con=$con;
}
public function product(){
$con=$this->con;
$result = mysqli_query($con,"SELECT * FROM attribute_id")or die (mysql_error());
while ($row = $result->fetch_assoc()) {
$arr[]= $row;
}
return $arr;
}
}
?>
索引.php
<?php
include "classes/db_class.php";
$con=new con();
$products= new db($con);
$product_data= $products->product();
print_r($product_data);
?>
看看这里的语句,
$con=new con();
在这里,您实际上是在获取对当前对象的引用,而不是对连接处理程序的引用。在 con
类中创建单独的属性private $con
并将其用作连接处理程序,或者在类本身中创建连接db
。
方法(1):
配置.php
// your define() statements
class con {
private $con;
function __construct(){
$this->con=mysqli_connect(HOST, USER, PASSWORD, DATABASE);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getConnection(){
return $this->con;
}
}
db_class.php
// your db_class.php page will be as it is
索引.php
include "classes/db_class.php";
$con=new con();
$connection = $con->getConnection();
$products= new db($connection);
$product_data= $products->product();
print_r($product_data);
方法(2):
db_class.php
// there's no need of con class
// your define() statements here
class db {
private $con;
function __construct() {
$this->con=mysqli_connect(HOST, USER, PASSWORD, DATABASE);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function product(){
$result = mysqli_query($this->con,"SELECT * FROM attribute_id")or die (mysql_error());
while ($row = $result->fetch_assoc()) {
$arr[]= $row;
}
return $arr;
}
}
索引.php
include "classes/db_class.php";
$products= new db();
$product_data= $products->product();
print_r($product_data);
混淆可能来自对许多事情使用相同的名称......但是,传递给new db($con)
的$con
是在 index.php 中创建的类 con 的实例。它应该是在类 con 的构造函数中创建的$con
...