Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

MySQL

phpMyAdminがつかえるとして以下話をする。

MySQLにパスワードを設定している場合は
phpMyAdmin/config.inc.php

$cfg['Servers'][$i]['user']          = '*****'; 
$cfg['Servers'][$i]['password']      = '****';

を設定する。

phpMyAdminでデータベース作成

mydata 照合順序 utf8_nicode_ci

テーブル作成

boards フィールド数4

フィールド設定

id INT PRIMARY A_I
name VARCHAR(255) Null
title VARCHAR
content TEXT
CREATE TABLE `mydata`.`boards` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(255) NULL , `title` VARCHAR(255) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;

ダミーレコード入力

挿入で適当に数件入れる。

INSERT INTO `boards` (`id`, `name`, `title`, `content`) VALUES (NULL, 'poi', 'asdasd', 'fawefsfawefaewf');
INSERT INTO `boards` (`id`, `name`, `title`, `content`) VALUES (NULL, 'piopoi', 'asdasd', 'ddddddddddwwwwwssssxxxx');

CakePHPのデータベースファイルをMySQLに変更する

Config/app.php

    'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            /**
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',
            'username' => '****',
            'password' => '****',
            'database' => 'mydata',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,
            'quoteIdentifiers' => false,
            'url' => env('DATABASE_URL', null),
        ],

表示用意

例によってコントローラ用意

<?php

namespace App\Controller;

class BoardsController extends AppController {
  public function index() {
    $data = $this->Boards->find('all');
    $this->set('data', $data);
  }
}

?>

エンティティとテーブル用意

<?php
  namespace App\Mode\Entity;

  use Cake\ORM\Entity;

  class Board extends Entity
  {
    protected $_accessible = [
      '*' => true,
      'id' => false
    ];
  }
?>
<?php
  namespace App\Model\Table;

  use Cake\ORM\Table;

  class BoardsTable extends Table {
    
  }

  ?>

ビューの作成
Template/Boards/index.ctp

<h1>DataBase</h1>

<table>
<tr>
  <th>ID</th>
  <th>Title</th>
  <th>Content</th>
</tr>

<?php
$arr = $data->toArray();
for ($i = 0;$i < count($arr);$i++) {
  echo $this->Html->tableCells(
      $arr[$i]->toArray(),
      ['style' => 'background-color:#f0f0f0'],
      ['style' => 'font-weight:bold'],
      true);
}
?>

</table>