I'm learning kohana 3.3. I'm working on the model part. Basic query. But i don't know how to display the results i got from a query.
Here's the model.
APPPATH/classes/model/people.php
class Model_People extends Model {
public function show_data() {
$query = DB::query(Database::SELECT, 'SELECT * FROM people');
return $query;
}
}
APPPATH/classes/controller/people.php
class Controller_People extends Controller {
public function action_index() {
$model = Model::factory('people');
$view = View::factory('base_template');
$model->user = $model->show_data();
$this->response->body($view);
}
}
APPPATH/views/base_template.php
<?php
foreach($user as $row) {
echo "<h2>".$row['Name']."</h2>";
}
?>
I don't want to use ORM I'm using QUERY BUILDER. When I run the code it says variable user not defined. How do I display the results correctly? thanks.
Since you are learning Kohana, I would suggest using ORM, Kohana offers quite a powerful module for this.
After enabling the module you can use it like this
Model_People
class Model_People extends ORM {
}
Controller_People
public function action_index() {
$people = ORM::factory('People')->find_all();
$view = View::factory('base_template');
$view->people = $people;
$this->response->body($view);
}
base_template
<?php foreach ($people as $person) : ?>
<h2><?php echo $person->Name; ?></h2>
<?php endforeach; ?>
ORM offers many advantages, such as relationships, validation and filters. Without you having to write complex additional code (such as DB expressions).
Additionally when working on views, you might want to use a Controller that extends Controller_Template instead of Controller
Try this
class Controller_People extends Controller {
public function action_index() {
$model = Model::factory('people');
$view = View::factory('base_template');
$view->user = $model->show_data();
$this->response->body($view);
}
}
then loop in view
<?php
foreach($user as $row) :
echo "<h2>".$row['Name']."</h2>";
endforeach;
?>
Related
How should I add my model into my controller to display the values in drop down ?
The error I get: Invalid argument supplied for foreach()
I didn't use any framework. Just native php. I am new in MVC and PHP please help!
My Controller:
<?php
class Index extends Controller {
function __construct(){
parent::__construct();
}
function index(){
$landArray = $this->model->fetchData();
$this->view->render('index/index');
var_dump($landArray); // display all row in database
}
}
Model:
<?php
class Index_Model extends Model {
function __construct(){
parent::__construct();
}
function fetchData(){
$selectIsland = $this->connection->prepare("SELECT island_id, island
from island" );
$selectIsland->setFetchMode(PDO::FETCH_ASSOC);
$selectIsland->execute();
$islandResult = $selectIsland->fetchAll();
return $islandResult;
}
}
View:
<select>
<option value="">--- Select Island---</option>
<?php
foreach($islandResult as $row){
echo '<option value="'.$row['island_id'].'">'.$row['island'].'</option>';
endforeach
}?>
</select>
This is my library View and render method.
<?php
class View {
function __construct(){
}
public function render($name, $noInclude = false, $landArray){
if($noInclude == true){
require 'views/'.$name.'.php';
}else{
require 'views/header.php';
require 'views/'.$name.'.php';
require 'views/foother.php';
}
}
}
}
You never called fetchData() method of your model. In MVC controller controls everything. in your controller you have to call methods from model. then pass those to your view file.
<?php
class Index extends Controller {
function __construct(){
parent::__construct();
}
function index(){
$landArray = $this->model->fetchData();
$this->view->render('index/index', false, array('islandResult' => $landArray)); // as we are sending param to view and render accept that as 3rd param so we need to specify the 2nd param too!
}
}
Model:
<?php
class Index_Model extends Model {
function __construct(){
parent::__construct();
}
function fetchData(){
$selectIsland = $this->connection->prepare("SELECT island_id, island
from island" );
$selectIsland->execute();
$islandResult = $selectIsland->fetchAll();
return $islandResult; //if you need something to pass to view from db first you have to pass it to controller from model
}
}
View:
<select>
<option value="">--- Select Island---</option>
<?php
foreach($islandResult as $row){
echo '<option value="'.$row['island_id'].'">'.$row['island'].'</option>';
}
?>
</select>
View/Render Library Method:
class View {
function __construct(){
}
public function render($name, $noInclude = false, $arrayParam = array()){ //look closely...here i've made 3rd parameter as default argument so that your other codes which don't need to send param to view works smoothly.
if(count($arrayParam) > 0){
extract($arrayParam);
}
if($noInclude == true){
require 'views/'.$name.'.php';
}else{
require 'views/header.php';
require 'views/'.$name.'.php';
require 'views/foother.php';
}
}
}
Now you'll be able to use parameters in view which you are sending from controller. whatever you pass as array key in controller can be used as variable in view now.
N.B: check my comments from code.
<?php
class Page extends Eloquent {
}
class Article extends Page {
function __construct($attributes = []) {
parent::__construct($attributes);
$this->where('type', 'article');
}
}
$articles = Article::all();
// SELECT * FROM pages WHERE type = 'article'
The page table has many types of data, I want to separate these data by model class, I tried the above query but where() function isn't even being called in __constructor()
You simply want implement scope in Model. So check Query Scope but It must be defined in the model class. If you want a seperate class that uses that scope as the basis for querying check out global scope. https://softonsofa.com/laravel-how-to-define-and-use-eloquent-global-scopes/
<?php
class Page extends Eloquent {
}
class Article extends Page {
function __construct($attributes = []) {
if($attributes) {
$attributes['type'] = 'article';
}
parent::__construct($attributes);
}
public function newQuery() {
return parent::newQuery()->where('type', 'article');
}
}
$articles = Article::all();
// SELECT * FROM pages WHERE type = 'article'
Ok I have a simple question I am using codeigniter frame work to create a simple blog. When I set up just a controller and a view I can print my database information (blog roll) to my view just fine. When I use the model controller view method i fail.
Here is what I would like to implement in to a method controller view setup.
my original view that works:
<?php
//is there an array from your search form?
if($_GET){
$books = $this->db->get('blog');//query the blog table in the database
if($books->num_rows() < 1)//are there clients to show?
{
echo 'There are no blog post'; //error message if no post
}
else
{
foreach(result() as $row)//loop through the blog
{
echo $row->title."<br>";//display each titles info
}
}
}
?>
This is what i have set for my New model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog_Model extends CI_Model {
function get($args = null)
{
$query = $this->db->get('blog');
return $query->result();
foreach(result() as $row)//loop through the books
}
function insert($data)
{
$this->db->insert('blog', $data);
}
function update($data,$id)
{
$this->db->where("id",$id);
$this->db->update('blog', $data);
}
function delete($id)
{
$this->db->where("id",$id);
$this->db->delete('blog');
}
}
this is my new controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog->get();
$this->load->view('blog',$data);
}
}
I am not sure what to do for my new view? I just want to echo the blog roll to the view
Well you´re doing a foreach in the model after the return function.
So what you return is just this:
$query->result()
You may should do the foreach in the view, this would be better placed as a model just should just return and not process information. Best place would be in this case the controller or may view - depending on how strict you are.
I did not work with CodeIgniter for a while so may try this:
Controller:
class Blog extends CI_Controller
{
public function index()
{
$this->load->model('blog_model', 'blog');
$data['blogs'] = $this->blog_model->get()->result();
$this->load->view('blog',$data);
}
}
The View
Here goes some text...
<?php
foreach($blogs as $post)
{
echo $post['someData'];
echo $post['someData2'];
}
?>
After all this code...
May you want to lookup this (CodeIgniter Doc).
Hope this helps. Try to
Controller:
$data['blogs'] = $this->blog_model->get();
Even though you load the model in order to call its function you must pass its name.
Model:
Must always have result() or row() when query are applied.
Hope this helps in your endeavors
EDIT: With the code below now, I am unsure on how to print out the bookmarks and the tags correctly
I’m completely new to CI and I have recently hit a road block. I’m very unsure how I would go about passing a function argument from the view file to the controller so I could use it on a function?
I have a foreach loop on the view going through the all the items passed by function get_latest_bookmarks. That function returns a ID for each item and I am wanting to use this with another function called get_bookmark_tags which will get the tags of the bookmark from another table. I have provided the code I have done so far below.
Model:
<?php
class Bookmark_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_latest_bookmarks($limit)
{
// Load Database
$this->load->database();
// Query Database
$query = $this->db->get('Bookmark', $limit);
// Return Result
return $query;
}
function get_bookmark_tags($id)
{
// Load Database
$this->load->database();
$query = $this->db->query('SELECT Tag.Title
FROM `Tag`
INNER JOIN BookmarkTag
WHERE BookmarkTag.BookmarkID = "'.$id.'" AND Tag.TagID = BookmarkTag.TagID');
return $query;
}
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// Load URL Helper
$this->load->helper('url');
// Load User Library
$this->load->library('ion_auth');
// Is User Logged In
if ($this->ion_auth->logged_in())
{
$data['user'] = $this->ion_auth->get_user_array();
}
else
{
redirect('auth/login');
}
// Load Bookmark Model
$this->load->model('Bookmark_model');
// Create Arrays
$bookmarks = array();
$tags = array();
// Query Database
$query = $this->Bookmark_model->get_latest_bookmarks(4);
//
foreach ($query->result() as $row) {
array_push($tags, $this->Bookmark_model->get_bookmark_tags($row->BookmarkID));
array_push($bookmarks, $row);
}
$data['tags_latest'] = $tags;
$data['bookmarks_latest'] = $bookmarks;
$this->load->view('welcome_message', $data);
}
}
View:
<h1>Latest Bookmarks</h1>
<?php foreach ($bookmarks_latest as $bookmark): ?>
<?php print_r($bookmark); ?>
<?php print_r($tags_latest->result()); ?>
<?php endforeach; ?>
You should do that in your Controller before you are passing the data to the View.
Try with something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
// Load Model
$this->load->model('Bookmarks');
// Get Latest Bookmarks
$query = $this->Bookmarks->get_latest_bookmarks(4);
$bookmarks = array();
$tags = array();
foreach ($query->result() as $row) {
$bookmark_query = $this->Bookmarks->get_bookmark_tags($row->id);
$bookmark_arr = array();
foreach (bookmark_query->result() as $bookm) {
array_push($bookmark_arr, $bookm);
}
array_push($tags, $bookmark_arr);
array_push($bookmarks, $row);
}
$data['tags'] = $tags;
$data['bookmarks'] = $bookmarks;
// Load and Pass Data into View
$this->load->view('welcome_message', $data);
}
}
You don't.
The point in using a Framework is to default to proper standards. CodeIgniter follows a loose MVC pattern but you should never pass things from the view to the controller.
You can do it, but if you do it you'll be getting into a spaghetti mess pretty soon.
Grab the ID's on the controller. Even if it implicates running the same loop twice. You'll thank yourself latter on.
Can anyone please explain me the object flow in codeigniter MVC ? I can see for example when I put the followong code in controller it works, but i am not being able to figure out which part of this goes in model in vews. I tried several ways but coudn't. When i use the example codes from other it works but myself i am getting confused. Please help
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
That would translate into something like:
Model:
class SomeModel extends Model {
function SomeModel() {
parent::Model();
}
function get_some_data() {
return $this->db->query('some_query')->result_array();
}
}
Controller:
class SomeController extends Controller {
function SomeController() {
parent::Controller();
}
function index() {
$this->load->model('SomeModel');
$some_data = $this->SomeModel->get_some_data();
$this->load->view('some_view');
}
}
View:
foreach($some_data as $data) {
echo $data->title;
echo $data->name;
echo $data->body;
}
However, for your communication between controller and view I would recommend using a template parser such as Dwoo or Twig (I don't like the one that comes with CI).
On the controller part I was doing:
class SomeController extends Controller {
function SomeController() {
parent::Controller();
}
function index() {
}
function show_data(){
$this->load->model('SomeModel');
$some_data = $this->SomeModel->get_some_data();
$this->load->view('some_view.php');
$this->index()
}
}
is that not the way to do it when we have many function ? When i look at other's code I see something like that or I am wrong ?