猿问

为什么不在php中使用数据库函数类

我采用了这个例子中给出的代码:PHP 数据库连接类


但是我使用上面的链接更改了代码,如下所示:


class Database {

    public function connect() {

        define('DB_HOST', 'localhost');

        define('DB_NAME', 'university');

        define('DB_USER', 'root');

        define('DB_PASSWORD', 'root');

        $db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);

    }

}

function Information(){

    Database::connect();

    $query = "SELECT * FROM student WHERE id "; $result = mysqli_query($db, $query);

        while($row = mysqli_fetch_array($result)) {

            echo $row['name'];

        }

}

Information();

它给出了错误:


Notice: Undefined variable: db in /Applications/XAMPP/file.php on line 12.

可能是什么原因,我做错了什么?


Cats萌萌
浏览 84回答 2
2回答

智慧大石

创建一个所有方法都可以共享的属性:<?phpclass Database&nbsp;{&nbsp; &nbsp; private $db;&nbsp; &nbsp; public function __construct()&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; define('DB_HOST', 'localhost');&nbsp; &nbsp; &nbsp; &nbsp; define('DB_NAME', 'university');&nbsp; &nbsp; &nbsp; &nbsp; define('DB_USER', 'root');&nbsp; &nbsp; &nbsp; &nbsp; define('DB_PASSWORD', 'root');&nbsp; &nbsp; &nbsp; &nbsp; $this->db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);&nbsp; &nbsp; }&nbsp; &nbsp; public function query($sql)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return mysqli_query($this->db, $query);&nbsp; &nbsp; }}然后重构你的功能function Information(){&nbsp; &nbsp; $db = new Database();&nbsp; &nbsp; $sql = "SELECT * FROM student WHERE id ";&nbsp;&nbsp; &nbsp; $result = $db->query($sql);&nbsp; &nbsp; while($row = mysqli_fetch_array($result)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;echo $row['name'];&nbsp; &nbsp; }}Information();

哔哔one

该变量db对于这一行的函数是未知的:由于$db是类属性,只需将其创建为类中的变量&nbsp;private&nbsp;$db;并将其设置在连接函数中,如下所述delboy1978uk:$this->db&nbsp;=&nbsp;mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
随时随地看视频慕课网APP
我要回答