0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CodeIgniter 4.4.1 でMariaDB を使う

Posted at

こちらで作成したコードに追加して、MariaDB を使います。
CodeIgniter 4.4.1 の使い方

参考ページ
Build Your First Application / News Section

ライブラリーのインストール

sudo apt install php-mysqli

MariaDB の準備

データベース ci4tutorial
ユーザー scott
パスワード tiger123

データベースに接続できることを確認

mariadb -uscott -ptiger123 ci4tutorial
$ mariadb -uscott -ptiger123 ci4tutorial
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 38
Server version: 10.11.2-MariaDB-1 Ubuntu 23.04

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

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

MariaDB [ci4tutorial]>

テーブルの作成

CREATE TABLE news (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(128) NOT NULL,
    slug VARCHAR(128) NOT NULL,
    body TEXT NOT NULL,
    PRIMARY KEY (id),
    UNIQUE slug (slug)
);

データの挿入

INSERT INTO news VALUES
(1,'Elvis sighted','elvis-sighted','Elvis was sighted at the Podunk internet cafe. It looked like he was writing a CodeIgniter app.'),
(2,'Say it isn\'t so!','say-it-isnt-so','Scientists conclude that some programmers have a sense of humor.'),
(3,'Caffeination, Yes!','caffeination-yes','World\'s largest coffee shop open onsite nested coffee shop for staff only.');

データが挿入されたことを確認

MariaDB [ci4tutorial]> select * from news;
+----+--------------------+------------------+-------------------------------------------------------------------------------------------------+
| id | title              | slug             | body                                                                                            |
+----+--------------------+------------------+-------------------------------------------------------------------------------------------------+
|  1 | Elvis sighted      | elvis-sighted    | Elvis was sighted at the Podunk internet cafe. It looked like he was writing a CodeIgniter app. |
|  2 | Say it isn't so!   | say-it-isnt-so   | Scientists conclude that some programmers have a sense of humor.                                |
|  3 | Caffeination, Yes! | caffeination-yes | World's largest coffee shop open onsite nested coffee shop for staff only.                      |
+----+--------------------+------------------+-------------------------------------------------------------------------------------------------+
3 rows in set (0.001 sec)

MariaDB [ci4tutorial]>

MariaDB への接続情報

.env
(省略)
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = ci4tutorial
database.default.username = scott
database.default.password = tiger123
database.default.DBDriver = MySQLi
# database.default.DBPrefix =
# database.default.port = 3306
(省略)

Model

app/Models/NewsModel.php
<?php

namespace App\Models;

use CodeIgniter\Model;

class NewsModel extends Model
{
    protected $table = 'news';

    public function getNews($slug = false)
    {
        if ($slug === false) {
            return $this->findAll();
        }

        return $this->where(['slug' => $slug])->first();
    }
}

Controller

app/Controllers/News.php
<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class News extends BaseController
{
    public function index()
    {
        $model = model(NewsModel::class);


        $data = [
            'news'  => $model->getNews(),
            'title' => 'News archive',
        ];

        return view('templates/header', $data)
            . view('news/index')
            . view('templates/footer');
    }

    public function show($slug = null)
    {
        $model = model(NewsModel::class);

	$data['news'] = $model->getNews($slug);

	if (empty($data['news'])) {
            throw new PageNotFoundException('Cannot find the news item: ' . $slug);
        }

        $data['title'] = $data['news']['title'];

        return view('templates/header', $data)
            . view('news/view')
            . view('templates/footer');
    }
}

View

app/Views/news/index.php
<h2><?= esc($title) ?></h2>

<?php if (! empty($news) && is_array($news)): ?>

    <?php foreach ($news as $news_item): ?>

        <h3><?= esc($news_item['title']) ?></h3>

        <div class="main">
            <?= esc($news_item['body']) ?>
        </div>
        <p><a href="/news/<?= esc($news_item['slug'], 'url') ?>">View article</a></p>

    <?php endforeach ?>

<?php else: ?>

    <h3>No News</h3>

    <p>Unable to find any news for you.</p>

<?php endif ?>
app/Views/news/view.php
<h2><?= esc($news['title']) ?></h2>
<p><?= esc($news['body']) ?></p>

Routing Rule

app/Config/Routes.php
<?php

use CodeIgniter\Router\RouteCollection;
use App\Controllers\News;
use App\Controllers\Pages;

/**
 * @var RouteCollection $routes
 */
$routes->get('/', 'Home::index');

$routes->get('news', [News::class, 'index']);           // Add this line
$routes->get('news/(:segment)', [News::class, 'show']); // Add this line

$routes->get('pages', [Pages::class, 'index']);
$routes->get('(:segment)', [Pages::class, 'view']);

サーバーを起動

php spark serve

ブラウザーで、
http://localhost:8080/news/
にアクセス

image.png

確認したバージョン

$ php -v
PHP 8.1.12-1ubuntu4.3 (cli) (built: Aug 17 2023 17:37:48) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.12-1ubuntu4.3, Copyright (c), by Zend Technologies
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?