我有3节课: 这是主要的DB类 - 如果将在其他两个类中使用。
class db {
const DBHOST = 'Localhost';
const DBNAME = 'project';
const DBUSER = 'root';
const DBPASS = '';
public $db=array();
private $_dpt = array('fr'=>'','en'=>'_en');
public $db_pref = 'fr';
public $db_name;
public function __construct(){
}
public function connect_db(){
if(!isset($this->db[$this->db_pref])){
$this->db[$this->db_pref] = mysql_connect (self::DBHOST, self::DBUSER, self::DBPASS) or die (mysql_errno.' : Can`t connect to this DB');
mysql_select_db(self::DBNAME.$this->_dpt[$this->db_pref], $this->db[$this->db_pref]) or die (mysql_errno.' : Can`t select this DB');
mysql_query("SET NAMES utf8");
}
}
这是我的团队课程:
require_once('db.php');
class crud extends db {
public function __construct(){
$this->lang = $_SESSION['user_lang_type']; // fr or en
parent::__construct();
if(isset($p['db']) && isset($p['db_pref'])){
// I put here old db conn. to new object for economy
$this->db_pref=$p['db_pref'];
$this->db=$p['db'];
if(isset($p['prevent']) && $p['prevent']!=$p['db_pref']){
// if isset db_prevent - I connect to the project_fr db only
$this->db_pref=$p['prevent'];
$this->connect_db();
}
} else $this->connect_db();
}
// reset prevented database
public function resetPreventDB($db=false){
$this->db_pref=$this->lang;
if($db) foreach($db as $k=>$v){ if(!isset($this->db[$k])) $this->db[$k]=$v; }
}
public function getData(){
// this is shorted version of my crud query
// here I use link to selected db $this->db[$this->db_pref]
return mysql_query('select * from advertice',$this->db[$this->db_pref]);
}
} 这是我的第三个类 - 它使用CRUD类的连接从所选数据库加载数据:
class Advertice extends crud {
private $route;
public $cont;
public function __construct(){
global $crud;
parent::__construct(array('db'=>$crud->db,'db_pref'=>$crud->db_pref,'prevent'=>'fr'));
$this->getList($p);
}
public function getList(){
$q = $this->getData();
global $crud;
// this didnt work - if db is FR it can be changed to EN
$crud->resetPreventDB($this->db);
}
}
include_once 'crud.php';
include_once 'advertice.php';
$crud = new crud();
$crud->set = array();
// For ex. now I am in project_en database
$crud->getData() - will return data from project_en
$crud->set['ads'] = new Advertice(); // get data from project_fr
$crud->getData() // will return data from project_fr - but I call $crud->resetPreventDB() in Advertice->getList().
我真的不知道为什么$ crud-> resetPreventDB()不工作 - 但我真的不会这个代码,因为这个bug会停止我所有创业公司的开发。非常感谢您的理解和帮助帮助)谢谢。
答案 0 :(得分:0)
Mate,您正在调用函数getData()
,但在此函数中没有对resetPreventDB()
函数的引用。
为什么要更改数据库?
也许你想调用函数getList()
而不是getData()
?
顺便说一句:如果你的代码不使用全局变量会更好看,就像那样:
public function getList(){
$q = $this->getData();
$this->resetPreventDB($this->db);
return $q;
}
作为一般建议 - 考虑使用任何PHP框架。
所有类似的问题很久以前就已得到解决,并且受到许多开发人员的广泛测试
在初始学习曲线之后,您将能够快速发展至少10倍
如果您需要为特定框架提供建议 - 请询问。