ci高級用法篇之連接多個數據庫

 

2015年07月26日 16:27:40 dongxie548 閱讀數:6225

 版權聲明:本文爲博主原創文章,轉載請註明出處和作者名,尊重別人也是尊重自己 https://blog.csdn.net/u011250882/article/details/47065633

在我們的項目中有時可能需要連接不止一個數據庫,在ci中如何實現呢?

我們在本地新建了兩個數據庫,如下截圖所示:

修改配置文件database.php文件爲如下格式(讀者根據自己數據庫的情況修改相應參數的配置):

 


 
  1. <?php

  2. defined('BASEPATH') OR exit('No direct script access allowed');

  3.  
  4. /*

  5. | -------------------------------------------------------------------

  6. | DATABASE CONNECTIVITY SETTINGS

  7. | -------------------------------------------------------------------

  8. | This file will contain the settings needed to access your database.

  9. |

  10. | For complete instructions please consult the 'Database Connection'

  11. | page of the User Guide.

  12. |

  13. | -------------------------------------------------------------------

  14. | EXPLANATION OF VARIABLES

  15. | -------------------------------------------------------------------

  16. |

  17. | ['dsn'] The full DSN string describe a connection to the database.

  18. | ['hostname'] The hostname of your database server.

  19. | ['username'] The username used to connect to the database

  20. | ['password'] The password used to connect to the database

  21. | ['database'] The name of the database you want to connect to

  22. | ['dbdriver'] The database driver. e.g.: mysqli.

  23. | Currently supported:

  24. | cubrid, ibase, mssql, mysql, mysqli, oci8,

  25. | odbc, pdo, postgre, sqlite, sqlite3, sqlsrv

  26. | ['dbprefix'] You can add an optional prefix, which will be added

  27. | to the table name when using the Query Builder class

  28. | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection

  29. | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.

  30. | ['cache_on'] TRUE/FALSE - Enables/disables query caching

  31. | ['cachedir'] The path to the folder where cache files should be stored

  32. | ['char_set'] The character set used in communicating with the database

  33. | ['dbcollat'] The character collation used in communicating with the database

  34. | NOTE: For MySQL and MySQLi databases, this setting is only used

  35. | as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7

  36. | (and in table creation queries made with DB Forge).

  37. | There is an incompatibility in PHP with mysql_real_escape_string() which

  38. | can make your site vulnerable to SQL injection if you are using a

  39. | multi-byte character set and are running versions lower than these.

  40. | Sites using Latin-1 or UTF-8 database character set and collation are unaffected.

  41. | ['swap_pre'] A default table prefix that should be swapped with the dbprefix

  42. | ['encrypt'] Whether or not to use an encrypted connection.

  43. | ['compress'] Whether or not to use client compression (MySQL only)

  44. | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections

  45. | - good for ensuring strict SQL while developing

  46. | ['failover'] array - A array with 0 or more data for connections if the main should fail.

  47. | ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.

  48. | NOTE: Disabling this will also effectively disable both

  49. | $this->db->last_query() and profiling of DB queries.

  50. | When you run a query, with this setting set to TRUE (default),

  51. | CodeIgniter will store the SQL statement for debugging purposes.

  52. | However, this may cause high memory usage, especially if you run

  53. | a lot of SQL queries ... disable this to avoid that problem.

  54. |

  55. | The $active_group variable lets you choose which connection group to

  56. | make active. By default there is only one group (the 'default' group).

  57. |

  58. | The $query_builder variables lets you determine whether or not to load

  59. | the query builder class.

  60. */

  61.  
  62. $active_group = 'test';//默認連接test數據庫

  63. $active_record = TRUE;//是否開啓active record

  64.  
  65. $db['test'] = array(

  66. 'dsn' => '',

  67. 'hostname' => 'localhost',

  68. 'username' => 'root',

  69. 'password' => '',

  70. 'database' => 'test',

  71. 'dbdriver' => 'mysqli',

  72. 'dbprefix' => '',

  73. 'pconnect' => FALSE,

  74. 'db_debug' => TRUE,

  75. 'cache_on' => FALSE,

  76. 'cachedir' => '',

  77. 'char_set' => 'utf8',

  78. 'dbcollat' => 'utf8_general_ci',

  79. 'swap_pre' => '',

  80. 'encrypt' => FALSE,

  81. 'compress' => FALSE,

  82. 'stricton' => FALSE,

  83. 'failover' => array(),

  84. 'save_queries' => TRUE

  85. );

  86. //test2數據庫相關配置

  87. $db['test2'] = array(

  88. 'dsn' => '',

  89. 'hostname' => 'localhost',

  90. 'username' => 'root',

  91. 'password' => '',

  92. 'database' => 'test2',

  93. 'dbdriver' => 'mysqli',

  94. 'dbprefix' => '',

  95. 'pconnect' => FALSE,

  96. 'db_debug' => TRUE,

  97. 'cache_on' => FALSE,

  98. 'cachedir' => '',

  99. 'char_set' => 'utf8',

  100. 'dbcollat' => 'utf8_general_ci',

  101. 'swap_pre' => '',

  102. 'encrypt' => FALSE,

  103. 'compress' => FALSE,

  104. 'stricton' => FALSE,

  105. 'failover' => array(),

  106. 'save_queries' => TRUE

  107. );

 

在applicaton/model目錄下創建兩個文件:score.php

 


 
  1. <?php

  2. class Score extends CI_Model {

  3.  
  4. private $tableName = 'score';

  5.  
  6. function __construct()

  7. {

  8. parent::__construct();

  9. }

  10.  
  11. public function getAllScores(){

  12. return $this->db->get($this->tableName);

  13. }

  14. }

和students.php

 

 


 
  1. <?php

  2. class Students extends CI_Model {

  3.  
  4. private $tableName = 'students';

  5.  
  6. function __construct()

  7. {

  8. parent::__construct();

  9. }

  10.  
  11. public function getAllStudents(){

  12. return $this->db->get($this->tableName);

  13. }

  14. }

修改welcome控制器:

 

 


 
  1. <?php

  2. defined('BASEPATH') OR exit('No direct script access allowed');

  3.  
  4. class Welcome extends ci_Controller {

  5.  
  6. /**

  7. * Index Page for this controller.

  8. *

  9. * Maps to the following URL

  10. * http://example.com/index.php/welcome

  11. * - or -

  12. * http://example.com/index.php/welcome/index

  13. * - or -

  14. * Since this controller is set as the default controller in

  15. * config/routes.php, it's displayed at http://example.com/

  16. *

  17. * So any other public methods not prefixed with an underscore will

  18. * map to /index.php/welcome/<method_name>

  19. * @see http://codeigniter.com/user_guide/general/urls.html

  20. */

  21. public function __construct(){

  22. parent::__construct();

  23. $this->load->model('students');

  24. $this->load->model('score');

  25. }

  26.  
  27. public function index()

  28. {

  29. var_dump($this->students->getAllStudents()->result());

  30. var_dump($this->score->getAllScores()->result());

  31. die('測試結束');

  32. }

  33. }


訪問http://localhost/ci2/地址,瀏覽器輸出如下截圖所示:

 

可以看到ci沒有找到score表,我們需要在score.php文件中用

$this->db = $this->load->database('test2', TRUE);

顯示指明score所在的數據庫:

 


 
  1. <?php

  2. class Score extends CI_Model {

  3.  
  4. private $tableName = 'score';

  5. private $db;

  6.  
  7. function __construct()

  8. {

  9. parent::__construct();

  10. $this->db = $this->load->database('test2', TRUE);

  11. }

  12.  
  13. public function getAllScores(){

  14. return $this->db->get($this->tableName);

  15. }

  16. }

再次訪問訪問http://localhost/ci2/地址,輸出結果如下截圖所示:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章