gpt4 book ai didi

php - 给出警告 : mysqli_query() expects parameter 1 to be mysqli, null。当我尝试将数据库作为 OOP 对象连接时

转载 作者:行者123 更新时间:2023-11-29 11:01:41 27 4
gpt4 key购买 nike

我有一个关于将我的数据库连接到我的 php 并获取数据的问题。错误是警告:

mysqli_query() expects parameter 1 to be mysqli, null given

这是我的 2 个文件,类和实现

我的代码:

<?php

class DB{
//this is my protected data
protected $db_hostname = 'localhost';
protected $db_username = 'root';
protected $db_password = '';
protected $db_name = 'blog';

public function connect(){
//connection to DB
$connect_db = mysqli_connect($this->db_hostname, $this->db_username, $this->db_password, $this->db_name) or die(mysqli_connect_error($connect_db));
//close the connection
mysqli_close($connect_db);
//for test
echo "Greate";
}
}
?>

第二个文件:-

$connection  = $db->connect();
$result = "SELECT * FROM blog_posts ";
$query = mysqli_query($connection, $result) or die(mysqli_error());

//loop through my data
while($row = mysqli_fetch_array($query)){

?>
<div class="well">
//print data
By: <?php echo $row->author ?>
<p><?php echo $row->title ?></p>
</div>
<?php } ?>


?>

最佳答案

函数需要如下所示:-

public function connect(){
//connection to DB
$connect_db = mysqli_connect($this->db_hostname, $this->db_username, $this->db_password, $this->db_name);
if(mysqli_connect_error()){ // you can use mysqli_connect_errorno() also
die(mysqli_connect_error()); // remove $connect_db
}else{
return $connect_db; // return connection object
}

}

也进行了如下更改:-

while($row = mysqli_fetch_assoc($query)){

?>
<div class="well">
//print data
By: <?php echo $row['author']; ?>
<p><?php echo $row['title']; ?></p>
</div>
<?php } ?>


?>

注意:- mysqli_fetch_array() 将为您提供索引+关联数组。而mysqli_fetch_assoc()只会给你关联数组,这使得你的结果数组更轻。谢谢

查看它以获得更好的错误报告:- http://php.net/manual/en/mysqli-driver.report-mode.php

关于php - 给出警告 : mysqli_query() expects parameter 1 to be mysqli, null。当我尝试将数据库作为 OOP 对象连接时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com