2 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
創(chuàng)建一個(gè)所有方法都可以共享的屬性:
<?php
class Database
{
private $db;
public function __construct()
{
define('DB_HOST', 'localhost');
define('DB_NAME', 'university');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
$this->db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
}
public function query($sql)
{
return mysqli_query($this->db, $query);
}
}
然后重構(gòu)你的功能
function Information()
{
$db = new Database();
$sql = "SELECT * FROM student WHERE id ";
$result = $db->query($sql);
while($row = mysqli_fetch_array($result)) {
echo $row['name'];
}
}
Information();

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
該變量db
對(duì)于這一行的函數(shù)是未知的:
由于$db
是類屬性,只需將其創(chuàng)建為類中的變量
private $db;
并將其設(shè)置在連接函數(shù)中,如下所述delboy1978uk
:
$this->db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
- 2 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)