自分用メモ
■cakephp 1.3 でDB連携してデータ取得するまで
------------------------------------------------------------
1. データベースにテーブルを作成
------------------------------------------------------------
mysql>
CREATE TABLE members ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
------------------------------------------------------------
※テーブル名に複数形sがついていることに注意
------------------------------------------------------------
2. モデルの作成
------------------------------------------------------------
$ vi app/models/member.php
------------------------------------------------------------
<?php
class Member extends AppModel
{
var $name="Member";
}
------------------------------------------------------------
3. コントローラの作成
------------------------------------------------------------
$ vi app/controllers/member_controller.php
------------------------------------------------------------
<?php
class MemberController extends AppController
{
public $scaffold;
}
------------------------------------------------------------
4. ブラウザで確認
------------------------------------------------------------
http://localhost/cakephp1.3/member
------------------------------------------------------------
■全レコード取得
------------------------------------------------------------
コントローラ
------------------------------------------------------------
$ vi app/controllers/member_controller.php
------------------------------------------------------------
<?php
class MemberController extends AppController
{
function index()
{
// all records
$results = $this->Member->find('all');
$this->set('results', $results);
}
}
------------------------------------------------------------
ビュー
------------------------------------------------------------
$ vi app/views/member/index.ctp
------------------------------------------------------------
<?php foreach($results as $v): ?>
<li><?php echo $v['Member']['id'] . $v['Member']['name']; ?></li>
<?php endforeach; ?>
------------------------------------------------------------
■1レコード取得
------------------------------------------------------------
コントローラ
------------------------------------------------------------
$ vi app/controllers/member_controller.php
------------------------------------------------------------
<?php
class MemberController extends AppController
{
function index()
{
// 1 record
$results = $this->Member->find('first', array('conditions'=>array('id'=>4)));
$this->set('results', $results);
}
}
------------------------------------------------------------
ビュー
------------------------------------------------------------
$ vi app/views/member/index.ctp
------------------------------------------------------------
<?php foreach($results as $v): ?>
<li><?php echo $v['id'] . $v['name']; ?></li>
<?php endforeach; ?>
------------------------------------------------------------