CodeIgniterフレームワークとBootstrap4で簡単な画面を作り、データベースアクセスを加えていきます。
DBのコネクションはAutoLoadにまかせる
CodeigniterのDBアクセスのために、絶対に設定が必要な設定ファイルがあります。
それが「application/config/database.php」です。
こんな感じで初期値が設定されています。
$active_group = 'default';
$query_builder = TRUE;$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
とりあえず、DBに接続するために変更が必要なのは以下の部分のみです。
'hostname' => 'localhost',
'username' => ''testuser,
'password' => 'testpassword',
'database' => 'dbname',
あと、もう一つ。
データベース接続はソースで明示的にコネクションをオープン、クローズすることもできますが、推奨はAutoLoadみたいです。
賢くコントロールします・・と、フレームワークの説明にも書いているので信じます。
AutoLoadを有効にするには「application/config/autoload.php」に以下の記述をします。
$autoload['libraries'] = array('database');
これで自動的にDBのコネクションが取得されます。
複数行データの取得と一覧表示をやってみる
作成するのは以下のような画面です。
取得対象のテーブルとデータは、以下の記事で作成したものと同じです。
Viewのヘダーとフッターは前回も利用したテンプレートをそのまま使い、中のデータだけを差し替える感じです。
コントローラクラス
Demos.php というコントローラを作ります。
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Demos extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('html'); $this->load->model('Demo_model'); } public function index($page = 'demobody') { if ( ! file_exists(APPPATH.'views/demos/'.$page.'.php')) { show_404(); } $data['title'] = ucfirst($page); $data['infotitle'] = "サンプルの一覧表です"; $data['info'] = $this->Demo_model->getTableData(); $this->load->view('templates/header', $data); $this->load->view('demos/'.$page, $data); $this->load->view('templates/footer', $data); } } ?>
モデルクラスの利用を追加しています。
コンストラクタで、他のヘルパークラスと同様に、モデルクラス(今回は、Demo_model)をロードします。
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('html');
$this->load->model('Demo_model');
}
ロードしたモデルは「$this->{モデルクラス名}->{メソッド名}」で実行します。
今回はモデルクラス名が「Demo_model」で、そこに「getTableData()」というメソッドを作っています。
なので、実行は。
$data['info'] = $this->Demo_model->getTableData();
みたいな感じになります。
モデルクラス
モデルクラス,Demo_model.php です。
<?php class Demo_model extends CI_Model{ function __construct() { parent::__construct(); } public function getTableData(){ $sql = "select * from demo where id <= ?"; $query = $this->db->query($sql, array(5)); return $query->result_array(); } } ?>
DBからデータを取ってきて、配列で返す。
やってることはそれだけです。
素のMysqliで同じ処理をしたものと比較してみます。
まず「Codeigniter」のケース
$sql = "select * from demo where id <= ?";
$query = $this->db->query($sql, array(5));
これと同じことを素のMysqliで書くと、こんな感じ。
if ($stmt = $this->db->get()->prepare("select * from demo where id <= ?")) {
$stmt->bind_param("i",$id);
$id = 5;
$isSuccess = $stmt->execute();
そして、「Codeigniter」ケースのその下の部分
return $query->result_array();
これを、素のMysqliで書くと。
if($isSuccess){
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)){
$ar_tbl[] = $row;}
return $ar_tbl;
}
こんな感じです。
Codeigniterの方がわかりやすくて、シンプルに書けるのは明確です。
CodeIgniterのDBアクセスには色々な方法が用意されてますが、これは一番シンプルなクエリメソッドを使う方法です。
個人的には、SQL文を直接書くこの方法が好きです。
リファレンスは「クエリ — CodeIgniter 3.2.0-dev ドキュメント」にあります。
でも。
もちろんSQLを直接書かない方法もあります。
クエリビルダクラスを使う方法です。
以下のリンクでリファレンスを見てお好みで。
クエリビルダクラス — CodeIgniter 3.2.0-dev ドキュメント
ビューのPHP
ヘダー部とフッター部はテンプレートのままなので省略します。
ボディ部のみ以下のようにします。
demobody.phpというファイルです。
<div class="row"> <div class="col text-center"> <h1><?php echo $infotitle; ?></h1> </div> </div> <div class="row"> <div class="col my-2 text-center"> <table class="table"> <thead> <tr> <th>NO</th> <th>名前</th> <th>性別</th> <th>生年月日</th> </tr> </thead> <tbody> <?php foreach ($info as $row) { print("<tr>"); print("<th>" . $row['id'] . "</th>"); print("<td>" . $row['name'] . "</td>"); print("<td>" . $row['sex'] . "</td>"); print("<td>" . $row['birth'] . "</td>"); print("</tr>"); } ?> </tbody> </table> </div> </div>
コントローラクラスで$data['info']にセットした配列(データベースから取得した値)を$infoにとして取得できます。
そのままforeachで処理して、行データを取り出して処理しています。
行データ($row)からは、テーブルのカラム名で値をとりだせます。
これで実行します。
ローカルホストで、プロジェクト名「ciprac」、コントローラクラスが「Demos」なので、以下のようなURLで表示できます。
本当なら、route.phpで設定して、もう少しスマートなURLで表示できるようにしたほうが良いのですが、個別でやってもしょうがないので、どっかでまとめてRoute設定の回みたいな感じでまとめて考えることにします。
ではでは。