使用mysqli和OOP获取错误

时间:2017-01-10 03:45:15

标签: php oop mysqli

我在下面粘贴的脚本中遇到错误。我不知道为什么我会得到它们并需要帮助。谢谢。

error displaying image

mysqli_fetch_assoc-的index.php

<?php
//mysqli connect here
include('mysqli_fetch_assoc.php');
$newbookings = new booking();
?>   
<div class="container">
    <table class="table table-hover text-center">
        <thead>
            <tr align="center">
                <th>Name</th>
                <th>Contact</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $newbookings->showBooking();

            while($row = mysqli_fetch_assoc($res)){//shows error here
            ?>
            <tr>
                <td><?php $row['name'];?></td>
                <td><?php $row['contact'];?></td>
                <td><?php $row['email'];?></td>
            </tr>
            <?php   
            }
            ?>  
        </tbody>
    </table>
</div>

mysqli_fetch_assoc.php:

<?php
class booking{
    function __construct(){
        $mysqli = mysqli_connect('localhost','root','admin','homestay');

        if(mysqli_connect_errno($mysqli)){
            echo "Connection failed".mysqli_connect_errno;
        }
    }

    function showBooking(){
        $res = mysqli_query($mysqli,"SELECT * FROM bookmyroom");//shows error here
        return $res;
    }
}
?>

1 个答案:

答案 0 :(得分:-1)

正如我评论的那样,这里特别指的是我用符号表示的地方:

<?php
class booking
    {
        # Create variable to pass inside the class
        private $mysqli;
        # I would look into dependency injection of the database instead of
        # creating connection right inside this class
        public function __construct()
            {
                #Store the connection to share with the rest of the class
                $this->mysqli = mysqli_connect('localhost','root','admin','homestay');
                # I would also check this whole statement here,
                # I don't think this is right. Try this.
                # Here is the page for this usage: http://php.net/manual/en/mysqli.connect-error.php
                if(!$this->mysqli) {
                    # You have to add "()" here------------------vv
                    echo "Connection failed".mysqli_connect_errno();
                }
            }

        public function showBooking()
            {
                # You get an error here because $mysqli is out of scope, but
                # using $this->mysqli would be fine
                return mysqli_query($this->mysqli,"SELECT * FROM bookmyroom");
            }
        # create a return method for the connection, especially if you
        # plan to use the connection outside the class. Again, injection
        # of a database class is more suitable...
        public function getConnection()
            {
                return $this->mysqli;
            }
    }

在另一页中你会这样做:

# Since "showBooking()" returns a query, so you need to assign to a variable
$res = $newbookings->showBooking();

我还应该注意,最好将数据库类传递/注入此类,而不是作为__construct()的一部分创建连接。另外,我会就连接类型做一个最终评论,我个人认为PDO更健壮,更易于使用,所以如果你刚开始,我会重新考虑使用PDO作为连接而不是{ {1}}

修改

由于我有一个时刻,这里你可能想要交替做:

<强> /defines.php

mysqli_*

<强> /config.php

<?php
# If you create some defines, you will more easily be able to alter
# your site structure without major rewriting
define('DB_HOST','localhost');
define('DB_NAME','homestay');
define('DB_USER','root');
define('DB_PASS','admin');
# These are directory helpers
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('CLASSES', ROOT_DIR.DS.'classes');

<强> /classes/Database.php

<?php
# If you create a config file that you include in every page at the top,
# you can keep your site more easily structured
#
# Include the defines to help keep the site consistent
require(__DIR__.DIRECTORY_SEPARATOR.'defines.php');
# Create session here if your site uses sessions
session_start();
# Create a class autoloader so you don't have to manually include class files.
# It does require that you place your classes in the same folder structure
spl_autoload_register(function($class) {
    # This converts your classes into directory paths to the class folder
    $path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class));
    # If the file exists, include it
    if(is_file($path))
        include_once($path);
});

<强> /类/预订

<?php
/*
** @description    Class creates a commonly used database connection
*/
class Database
    {
        private static $con;

        public function connect()
            {
                # If there is a connection already made, send back
                if(!empty(self::$con))
                    return self::$con;
                #I would encourage PDO here...
                self::$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
                if(!self::$con) {
                    die("Connection failed".mysqli_connect_errno());
                }
                # Send back connection for use
                return self::$con;
            }
    }

<强>的index.php

<?php
/*
** @description    This class is your booking class that receives the database
**                 to use, so you don't create it here, only use it here.
*/
class Booking
    {
        private $con;
        /*
        ** @param $con [object] Insert your Database connection here
        */
        public function __construct($con)
            {
                $this->con = $con;
            }

        public function showBooking()
            {
                $row = array();
                $query = mysqli_query($this->con,"SELECT * FROM bookmyroom");
                if(empty($query))
                    return $row;

                while($result = mysqli_fetch_assoc($query)) {
                    $row[] = $result;
                }

                return $row;
            }
    }