我試圖讓PHP來簡化我的數據庫連接,以便我可以修改代碼的一個區域並影響整個程序。以下是我有:調用一個非對象的成員函數query()在
PAGE:rdpa.php(A模塊頁面
/**************************/
/* Create System Settings */
/**************************/
/* Database Connection Settings */
$_SESSION['servername'] = "localhost";
$_SESSION['mysql_username'] = "username";
$_SESSION['mysql_password'] = "password";
$_SESSION['dbname'] = "mydb";
//Turn on Error Report. True = On/False = Off
//ErrorReporting(false);
//Display Error.kfkg
function ErrorReporting($ErrOn){
if ($ErrOn == true) {
//Show Error
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
}
}
/**************************************
Open Database Connection Function.
***************************************/
class db_class {
function db_conn() {
global $conn;
global $mysqli;
$conn = new mysqli($_SESSION['servername'], $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//return db_conn;
}
}
PAGE:testdb3.php
<?php
//Included file.
include 'modules/rdpa.php';
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
//connect to the database.
$sql = "SELECT id, region FROM tbl_region;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<td width="1"><label for="delete">
<input type="radio" name="region" id="region" value="'.$row["id"].'">
</label></td>';
echo '<td align="left" valign="top"><p>'.$row["region"].'</p></td></tr>';
}
}
?>
當我運行testdb3.php我得到以下錯誤:
致命錯誤:調用第15行的C:\ websites \ rdpa \ testdb3.php中的非對象上的成員函數query()
這是第15行:
//connect to the database.
$result = $conn->query($sql);
一些能告訴我什麼,我做錯了什麼?
試一試 註釋這兩行$ db_Class = new db_Class; $ conn =($ db_Class-> db_conn()); – JYoThI
請返回您的連接對象您的問題將解決從db_conn函數返回您的$ conn變量 –
它返回以下錯誤:注意:未定義的變量:第15行testdb3.php中的conn致命錯誤:調用成員函數query()on第15行的testdb3.php中的非對象 –