php扩展类连接mysql问题

时间:2014-06-25 11:09:42

标签: php mysql

我有三个文件:

  • 的config.php
  • dbsng.php
  • bookclass.php

bookclass.php

include 'config.php';
include 'dbsngt.php';

/**
* Books
*/
class Books extends Database
{

public $db;
protected $title;
protected $id;
protected $code;

function __construct()
{
$this->db = self::obtain(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
if ($this->db->connect()){echo "YES connected";} else {echo "No connection";}

}

}

dbsngt.php:

class Database{

// debug flag for showing error messages
public  $debug = true;

// Store the single instance of Database
private static $instance;

private $server   = ""; //database server
private $user     = ""; //database login name
private $pass     = ""; //database login password
private $database = ""; //database name

private $error = "";

#######################
//number of rows affected by SQL query
public  $affected_rows = 0;

private $link_id = 0;
private $query_id = 0;


#-#############################################
# desc: constructor
private function __construct($server=null, $user=null, $pass=null, $database=null){
// error catching if not passed in
if($server==null || $user==null || $database==null){
    $this->oops("Database information must be passed in when the object is first created.");
}

$this->server=$server;
$this->user=$user;
$this->pass=$pass;
$this->database=$database;
}#-#constructor()


#-#############################################
# desc: singleton declaration
public static function obtain($server=null, $user=null, $pass=null, $database=null){
if (!self::$instance){ 
    self::$instance = new Database($server, $user, $pass, $database); 
} 

return self::$instance; 
}#-#obtain()


#-#############################################
# desc: connect and select database using vars above
# Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters
public function connect($new_link=false){
$this->link_id=@mysql_connect($this->server,$this->user,$this->pass,$new_link);

if (!$this->link_id){//open failed
    $this->oops("Could not connect to server: <b>$this->server</b>.");
    }

if(!@mysql_select_db($this->database, $this->link_id)){//no database
    $this->oops("Could not open database: <b>$this->database</b>.");
    }

// unset the data so it can't be dumped
$this->server='';
$this->user='';
$this->pass='';
$this->database='';
}


}

当我执行以下代码时,它会显示 无连接 即使在我无法建立连接之后,我仍然继承了数据库类

include 'classes/bookclass.php';
$obj = new Books();

1 个答案:

答案 0 :(得分:1)

将数据库连接变量的私有访问权限更改为public

public $server   = ""; //database server
public $user     = ""; //database login name
public $pass     = ""; //database login password
public $database = ""; //database name