続:掲示板を作ろう その3

コメント表示が終了したので、コメントの挿入のところをいじっていきます。

流れ

同じ名前のユーザーは、users テーブルに挿入しないようにしたい。なので

users テーブルに同じ名前がないかチェック
同じ名前がない時:名前とメールアドレスを挿入
同じ名前がある時:データの挿入過程をスキップ

コメントを comments テーブルに挿入

users テーブルに同じ名前がないかチェック
$name = array('name' => $this->input->post('name'));
$query = $this->db->get_where('users', $name);
$result = $query->row();

$this->db->get_where('users', $name); これは ここ を参照。
$query->row(); これは ここ を参照
post された名前を連想配列にして get_where('users', $name) で取得後 $query に格納。
$query->row() で結果の行を $result に格納。

同じ名前がない時:名前とメールアドレスを挿入
if (empty($result)) {
    $users = array(
        'name' => $this->input->post('name'),
        'email' => $this->input->post('email')
    );

    $this->db->insert('users', $users);

    $query = $this->db->get_where('users', $name);
    $result = $query->row();
}

if (empty($result)) {} 同じ名前があれば、$result には結果が入ってるので空じゃない。
$resultが空の時は、同じ名前がなかった時。
このままだと、comments テーブルに user_id を挿入するために必要な id がないので、再度 users テーブルから $name を使ってデータを取得。結果の行を $result に格納
それ以外の時は、users テーブルにはデータを挿入しないのでスキップ

コメントを comments テーブルに挿入。
$comments = array(
    'comment' => $this->input->post('comment'),
    'user_id' => $result->id
);

$this->db->insert('comments', $comments);

クエリの結果は配列じゃなく、オブジェクトで返る。
なので $result['id'] と記述せずに $result->id で id を取得
comments テーブルに comment と user_id を挿入すると。


これでデータの挿入もOKかなっと。

public function insert() {
    $name = array('name' => $this->input->post('name'));
    $query = $this->db->get_where('users', $name);
    $result = $query->row();

     if (empty($result)) {
        $users = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email')
        );

        $this->db->insert('users', $users);

        $query = $this->db->get_where('users', $name);
        $result = $query->row();
    }

    $comments = array(
        'comment' => $this->input->post('comment'),
        'user_id' => $result->id
    );

    $this->db->insert('comments', $comments);
}