class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$this->connection){
die("Database connection failed: ". mysql_error());
}
else {
$db_select = mysql_select_db(DB_NAME,$this->connection);
if(!$db_select){
die("Database connection failed: ". mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function fetch_array($result_set){
return mysql_fetch_array($result_set);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
private function confirm_query($result){
if(!$result){
die("Database query failed: ". mysql_error());
}
}
}
$db = new MySQLDatabase();
require_once("db.php");
class Read{
private $table_name= "real_estate";
private $column_name = "Property_type";
function __construct(){
}
public function pro_type() {
global $db;
var_dump($db);
echo "<select name='".$this->column_name."'>";
$sql = sprintf("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' AND COLUMN_NAME = '%s'",$this -> table_name,$this ->column_name);
$result = $db-> query($sql);
$row = $db->fetch_array($result);
$enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));
foreach($enumList as $value)
echo "<option value=$value>$value</option>";
echo "</select>";
}
}
require_once("read.php");
$link = new Read();
<?php
include '../inc/link.php';
$link -> pro_type();
?>
每件事看起来都很完美,但它会给出一条错误消息,说明正在非对象上调用查询。我实际上在另一个脚本中调用了$ db,但似乎没有任何工作。
答案 0 :(得分:0)
您的其他脚本中的调用是什么样的?应该是这样的:
require_once('includes/mysql.php'); // Where your MySQLDatabase class resides
if(class_exists('MySQLDatabase')) {
$db = new MySQLDatabase();
// Should work from here
$db->query("SELECT * FROM `table` WHERE 1");
} else {
die('Unable to load class.');
}