MyActiveRecord.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * 动态操作学校数据库基类
  4. */
  5. class MyActiveRecord extends CActiveRecord {
  6. static public $schoolId = 0;
  7. public function getDbConnection()
  8. {
  9. if (is_cli()) {
  10. return $this->cliConn();
  11. }else{
  12. return $this->webConn();
  13. }
  14. }
  15. /**
  16. * client连接
  17. * @return CDbConnection
  18. */
  19. public function cliConn() {
  20. $my_connection = null;
  21. if (self::$schoolId) {
  22. $getMyDate = BusinessDatabase::model()->find('school_id=:sid',array(':sid'=>self::$schoolId));
  23. $myDbDsn = 'mysql:host='.$getMyDate->database_host.';dbname='.$getMyDate->database_name;
  24. $my_connection = new CDbConnection($myDbDsn,$getMyDate->database_user,$getMyDate->database_password);
  25. if (!$my_connection) {
  26. throw new Exception('数据库连接失败');
  27. }
  28. $my_connection->emulatePrepare = true;
  29. $my_connection->enableProfiling = true;
  30. $my_connection->enableParamLogging = true;
  31. $my_connection->charset = 'utf8';
  32. $myDbDsn = null;
  33. }
  34. return $my_connection;
  35. }
  36. /**
  37. * web连接
  38. * @return CDbConnection
  39. */
  40. public function webConn() {
  41. $getMyDate = Yii::app()->session['myDatebase'];
  42. if (empty($getMyDate)) {
  43. $getDbConnect = BusinessDatabase::model()->find('school_id=:sid',array(':sid'=>Yii::app()->session['coachInfo']['school_id']));
  44. if (empty($getDbConnect)) {
  45. //Yii::app()->jump->error('登录异常请联系管理员!',$this->createUrl('login/index'));
  46. //删除session变量
  47. Yii::app()->session->clear();
  48. header('Location:/');
  49. exit();
  50. }
  51. Yii::app()->session['myDatebase'] = $getDbConnect;
  52. $getMyDate = $getDbConnect;
  53. unset($getDbConnect);
  54. }
  55. $myDbDsn = 'mysql:host='.$getMyDate->database_host.';dbname='.$getMyDate->database_name;
  56. $my_connection = new CDbConnection($myDbDsn,$getMyDate->database_user,$getMyDate->database_password);
  57. //$my_connection->active = true;
  58. //$my_connection = new CDbConnection('mysql:host=127.0.0.1:3307;dbname=spider_student','spider','wt24cuzGZ8HhEFSw');
  59. //$my_connection = new CDbConnection('mysql:host=192.168.1.232:3306;dbname=school','root','lc12345');
  60. $my_connection->emulatePrepare = true;
  61. $my_connection->enableProfiling = true;
  62. $my_connection->enableParamLogging = true;
  63. $my_connection->charset = 'utf8';
  64. $myDbDsn = null;
  65. return $my_connection;
  66. }
  67. }