サンプル集  >  PHP  >  CodeIgniter+MySQL
CodeIgniter+MySQL
2022/06/26

CodeIgniterでMySQLのテーブルの内容を表示してみます。

◆環境
OS Windows 10 Home 21H2 (64bit)
XAMPP v3.3.0

MySQLへログインしデータベースとテーブルを作成します。

XAMPPでApacheのほかにMySQLも起動します。

起動したら右側の「Shell」ボタンを押します。

Setting environment for using XAMPP for Windows.
ymlib@DESKTOP-55UPABF c:\xampp
#

MySQLへログインします。デフォルトではrootユーザーにパスワードの設定はなかったです。

# mysql -u root
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 22
Server version: 10.4.21-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input s
tatement.

MariaDB [(none)]>

CREATE DATABASEでmydbというデータベースを作ります。

MariaDB [(none)]> CREATE DATABASE mydb;
Query OK, 1 row affected (0.002 sec)

USEでmydbを指定します。

MariaDB [(none)]> USE mydb;
Database changed
MariaDB [mydb]>

CREATE TABLEでaisatsuというテーブルを作成します。

CREATE TABLE aisatsu (
        id int(11) NOT NULL AUTO_INCREMENT,
        text text NOT NULL,
        PRIMARY KEY (id)
);

実行します。

MariaDB [mydb]> CREATE TABLE aisatsu (
    ->         id int(11) NOT NULL AUTO_INCREMENT,
    ->         text text NOT NULL,
    ->         PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.015 sec)

INSERTでレコードを追加します。4件追加してみました。

INSERT INTO aisatsu(text) VALUES ("Hello");
INSERT INTO aisatsu(text) VALUES ("Good morning");
INSERT INTO aisatsu(text) VALUES ("Good afternoon");
INSERT INTO aisatsu(text) VALUES ("Good evening");

実行します。

MariaDB [mydb]> INSERT INTO aisatsu(text) VALUES ("Hello");
Query OK, 1 row affected (0.012 sec)

MariaDB [mydb]> INSERT INTO aisatsu(text) VALUES ("Good morning");
Query OK, 1 row affected (0.001 sec)

MariaDB [mydb]> INSERT INTO aisatsu(text) VALUES ("Good afternoon");
Query OK, 1 row affected (0.001 sec)

MariaDB [mydb]> INSERT INTO aisatsu(text) VALUES ("Good evening");
Query OK, 1 row affected (0.001 sec)

データベース情報の設定をします。database.phpはもとからあったものを書き換えました。最後が?>で閉じていないのが気になります。

database.php
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$active_group = 'default';
$db['default'] = array(
    'dsn'    => 'mysql:host=localhost:13306;dbname=mydb;charset=utf8',
    'hostname' => 'localhost:13306',
    'username' => 'root',
    'password' => '',
    'database' => 'mydb',
    'dbdriver' => 'pdo',
    '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['default']['port'] = 13306;

データベースの操作はコントローラではなくモデルに記述するようです。モデルはCI_Modelクラスを継承して実装します。今回はAisatsu_model.phpを作成しました。

Aisatsu_model.php
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
<?php
class Aisatsu_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    public function get_aisatsu()
    {
        $query = $this->db->get('aisatsu');

        return $query->result_array();
    }
}
?>

コントローラはAisatu.phpという名前で作成しました。

Aisatsu.php
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
<?php
class Aisatsu extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->model('aisatsu_model');
    }

    public function view()
    {
        $data['aisatsu'] = $this->aisatsu_model->get_aisatsu();

        $this->load->view('aisatsu/view', $data);
    }
}
?>

受け取ったデータをforeachで表示するview.phpを作成しました。

view.php
1: 
2: 
3: 
<?php foreach ($aisatsu as $aisatsu_item): ?>
    <?php echo $aisatsu_item['text']; ?><br />
<?php endforeach;

それぞれのphpファイルの配置は以下の通りです。

application/
+ config/
| + database.php
+ controllers/
| + Aisatsu.php
+ models/
| + Aisatsu_model.php
+ views/
  + aisatsu/
    + view.php

以下のURLへアクセスしてみます。

http://localhost/CodeIgniter-develop/index.php/aisatsu/view

データベースのaisatsuテーブルに登録されているレコードが全て表示されました。

▲ PageTop ■ Home


Copyright (C) 2022 ymlib.com