gpt4 book ai didi

php mysqli oops 概念连接

转载 作者:行者123 更新时间:2023-11-29 07:22:57 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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/

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