###前提・実現したいこと
CodeIgniterのコントローラーで取得したDBのデータをsmartyのテンプレートで使いたいです。
環境は、
CentOS6.4-x86_64
CodeIgniter2.2.6
mysql5.5.48
php5.4.45
smarty3.1.29
を使用しています。
###発生している問題・エラーメッセージ
上記の通り、CodeIgniterのコントローラーで取得したDBのデータをsmartyのテンプレートで使いたいのですが、私の書いたコードでは取得できなく困っています。
正しい記述方法をご存知の方、ご教授いただけないでしょうか・・・?
よろしくお願い致します。
2016/04/10 1:11 追記
申し訳ありません、一部ソースの添付間違いがあったため修正しました。
改めてお願い致します。
###該当のソースコード
●sample.php(コントローラー)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once(dirname(__FILE__).'/MY_Controller.php'); class Sample extends MY_Controller { public function __construct() { parent::__construct(); } // 設定画面 public function index() { $tpl = 'index'; // ユーザーデータを取得 $data['user_data'][] = array('user_id' => $row->user_id, 'user_name' => $row->user_name); $data = array(); foreach ($user_data_query->result() as $row) { $data[] = array($row->user_id => $row->user_name); } $smarty = new Smarty(); $smarty->assign('user_data', 'data'); print_r($data); $this->view($tpl . '.tpl', $data); } // 結果画面 public function result() { $tpl = 'result'; $this->view($tpl . '.tpl'); } } ?>
●index.tpl
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form method="post" action="/sample/result"> <label for="user_select">ユーザー情報</label> <select id="user_select"> {foreach from=$user_data key=user_id item=user_name} <option value="{$user_id}">{$user_name}</option> {/foreach} </select><br> <input type="submit" value="確認"> </form> </body> </html>
###試したこと
【2016/04/10 12:52 追加】
・配列「$data」の形を修正
・変数「user_data」に格納する値の記述方法を修正
●sample.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once(dirname(__FILE__).'/MY_Controller.php'); class Sample extends MY_Controller { public function __construct() { parent::__construct(); } // 設定画面 public function index() { $tpl = 'index'; // ユーザーデータを取得 $user_data_query = $this->db->query('SELECT * FROM tbl_m_user'); $data = array(); foreach ($user_data_query->result() as $row) { // 配列の形を修正 $data[$row->user_id] = $row->user_name; } $smarty = new Smarty(); // 格納する値の指定を修正 $smarty->assign('user_data', $data); print_r($user_data); $this->view($tpl . '.tpl', $user_data); } // 結果画面 public function result() { $tpl = 'result'; $this->view($tpl . '.tpl'); } } ?>
【2016/04/17 8:33 追加】
・$dataをassignの指定先を修正
●sample.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once(dirname(__FILE__).'/MY_Controller.php'); class Sample extends MY_Controller { public $user_data; public function __construct() { parent::__construct(); } // 設定画面 public function index() { // ユーザーデータを取得 $user_data_query = $this->db->query('SELECT * FROM tbl_m_user'); $data = array(); foreach ($user_data_query->result() as $row) { $data[$row->user_id] = $row->user_name; } print_r($data); $this->smarty->assign('user_data', $data); $this->smarty->display('index.tpl'); } // 結果画面 public function result() { $this->view('result.tpl'); } } ?>
回答2件
あなたの回答
tips
プレビュー