php mysqli oops概念连接

时间:2016-02-18 08:54:12

标签: php mysql function class oop

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>';
    }
} ?>

显示错误:

  

连接成功
  警告:mysqli_num_rows()期望参数1为mysqli_result,第10行的D:\ xampp \ htdocs \ test \ index.php中给出布尔值

任何解决方案?

3 个答案:

答案 0 :(得分:2)

构造函数应为:

  • 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>';
    }
} ?>

保持执行流程并逐点调试,以找出出错的地方。

答案 1 :(得分:0)

您无需使用mysqli_num_rows

  

mysqli_query失败时返回FALSE

$result = mysqli_query($conn, $sql);
// $result will give you true or false
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo 'Name : ' . $row['name'] . ' - Matric No : ' . $row['matric_no'] . '<br>';
    }
}
else{
    // check error
     printf("Error: %s\n", mysqli_error($conn));
} 

希望它会对你有所帮助:)。

答案 2 :(得分:0)

返回mysqli_query的值:

  

失败时返回FALSE。成功的SELECT,SHOW,DESCRIBE或   EXPLAIN查询mysqli_query()将返回一个mysqli_result对象。对于   其他成功的查询mysqli_query()将返回TRUE。

最有可能的是,您的查询出错,mysqli_query返回FALSE

检查mysqli_error($conn)是否有错误消息。