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.
Related
I am new in using Codeigniter as web api, I want to get this result
{"result":[{"id":"1","nama":"Orion","nomor":"08576666762"},{"id":"2","nama":"Mars","nomor":"08576666770"},{"id":"7","nama":"Alpha","nomor":"08576666765"}],"success":"1","message":"success"}
but instead I get this kind of result :
{"result":[[{"id":"1","nama":"Orion","nomor":"08576666762"},{"id":"2","nama":"Mars","nomor":"08576666770"},{"id":"7","nama":"Alpha","nomor":"08576666765"}]],"success":"1","message":"success"}
I wonder where am I get it wrong?
I am using codeigniter and my code below is from controller and models
m_server.php (modals)
<?php
Class M_server extends CI_Model {
function __construct(){
parent::__construct();
$this->load->database();
}
// buat view dashboard main
function dash_main1(){
$data = $this->db->query("
select *
from telepon
");
$result = array();
$result['result'] = array();
$result['success'] = "1";
$result['message'] = "success";
array_push($result['result'], $data->result());
return $result;
}
}
Rest_server.php (controller)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Rest_server extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_server');
}
public function index()
{
$this->load->helper('url');
$this->load->view('rest_server');
}
function dash_main1(){
$data=$this->m_server->dash_main1();
echo json_encode($data);
}
}
Remove this line (optional)
$result['result'] = array();
And change this line
$result['result'] = $data->result(); //result become the array
array_push add an element to an existing array
I have created a small project that display clothing items that coming from a database in CodeIgniter. The data is coming from the database and it's working and I have put a where condition to check the category and where condition doesn't work. Instead of displaying the specific results it displays all the database table results. I'm passing the category parameter through the url. I have autoloaded the database.
This is how i passed the parameter in home page when user click the Men's link
<a class="dropdown-item" href="<?php echo base_url();?>index.php/Products/view/mens">Men's</a>
This is the controller
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Products extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('GetData');
}
public function view()
{
$category_name = $this->uri->segment(3);
$this->GetData->get_data($category_name);
$result = $this->GetData->get_data();
$data['result'] = $result;
$this->load->view('products',$data);
}
}
/* End of file Products.php */
/* Location: ./application/controllers/Products.php */
?>
This is the model
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class GetData extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_data($category_name=0){
$query = $this->db->get_where('mens', array('category' => $category_name));
return $query->result();
}
}
/* End of file GetData.php */
/* Location: ./application/models/GetData.php */
?>
Database table fields - id,category,category_name,img_path,item_name
I used where condition to check whether category is equal to mens and if it is display the results..And there is one row with category = women in the table. But instead of displaying the specific results it displays all the results.
Model:
public function get_data($category_name){
$query = $this->db->get_where('mens', array('category' => $category_name));
return $query->result();
}
Controller:
public function view()
{
$category_name = $this->uri->segment(3);
$result = $this->GetData->get_data($category_name);
$data['result'] = $result;
$this->load->view('products',$data);
}
Check this.
Please check first value of $category_name exist or not.
// Remove $this->GetData->get_data($category_name); from controller as you have already defining this again. Not getting why you are calling same function twice in your controller.
Hi guys i have problem using two tables from same DB in one view. When i use only one of the tables it works but when i try to fetch both of them my view does not load. This is my model: schedule_model.php:
<?php
class Schedule_model extends CI_Model {
public function __construct()
{
}
public function get_schedules()
{
$this->db->select('schedule.id, schedule.name');
$this->db->from('Schedule');
$this->db->group_by("schedule.id");
$query = $this->db->get();
return $query->result_array();
}
public function get_subscheds()
{
$this->db->select('subsched.id, subsched.name, subsched.enable, subsched.from, subsched.to, subsched.mode, subsched.fcu1, subsched.fcu2, subsched.fcu3, subsched.pon, subsched.vt, subsched.sr, subsched.cet, subsched.pet, subsched.sab, subsched.ned');
$this->db->from('Subsched');
$this->db->group_by("subsched.id");
$query = $this->db->get();
return $query->result_array();
}
}
?>
This is the controller: schedule.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Schedule extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('schedule_model');
}
public function index()
{
if(!$this->session->userdata('loggedIn')){
redirect("login");
}
$data['schedules'] = $this->schedule_model->get_schedules();
//$data['subscheds'] = $this->schedule_model->get_subscheds();
$this->load->view('schedule', $data); //my view is also named schedule :)
}
}
?>
Notice that i have commented the line that calls the function which gets the elements from the second table. If i uncomment it, my view freezes. Otherwise it works fine with only one table. In my view i loop through elements in foreach loops. What could be the problem? Thanks
Hope this one help you..
$schedules = $this->schedule_model->get_schedules();
$subscheds = $this->schedule_model->get_subscheds();
$data['schedules'] = $schedules;
$data['subscheds'] = $subscheds;
## and then pass to view.
$this->load->view('schedule', $data);
Try this one..I have made some modification..You can access "schedules" as $schedules and "subscheds" as $subscheds in 'schedule' view you have defined.
$data['schedules'] = $this->schedule_model->get_schedules();
$data['subscheds'] = $this->schedule_model->get_subscheds();
This will load both datas from shedules table and subsheds table. and then you can load view with these data by..
$this->load->view('schedule', $data);
Now you can loop through $data by using $data['schedules'] and $data['subscheds'] to use db fields wherever necessary.
My problem is that I can't read a piece of data on an individual page. For example, on the front page, I have a number of jokes pulled in from the db; I want to be able to click on a joke and send the user to a url such as jokes.com/read/a-chicken-crossed-the-road. At the moment, it sends me to my custom 404 page with the url being jokes.com/read/1 (1 being the joke_id) and I haven't been able to get past this problem for a while, so I though I would try here.
Here is my setup :
main view:
<p class="joke-content"><?php echo $joke; ?></p>
read view:
<?php
foreach($results as $row){
echo "<li>$row->joke</li>";
echo "<li>$row->name</li>";
echo "<li>$row->date_added</li>";
}
?>
controller:
//constructor class enables a function called to be used in any function within this controller
function __construct(){
// Call the Controller constructor
parent::__construct();
$this->load->model('getjokes_m');
}
public function index(){
$this->read();
}
//main jokes functions grabs all the jokes in the database and orders them in their correct category
public function read(){
$data['results'] = $this->getjokes_m->readJokes($this->uri->segment(3));
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/read', $data);
$this->load->view('template/footer');
}
and finally my model:
function readJokes()
{
$query = $this->db->query('SELECT j.*, c.name FROM jokes j LEFT JOIN category c ON c.category_id = j.category_id WHERE joke_id = ?');
//displays the results if the table has data inside
return $query->result();
}
routes:
$route['default_controller'] = "top";
$route['404_override'] = 'not_found';
$route['register'] = 'login/register';
$route['logout'] = 'login/logout';
$route['admin'] = 'admin/login';
$route['noaccess'] = 'login/noaccess';
I think it might be the sql statement I am using, because it doesn't return any data.
If somebody could point me in the right direction as to why this is not working and to get the first 55 characters in the URL slug, it would be brilliant.
If I understand this problem correctly you want a slug as a parameter of your read() function.
you did not specify controllers name lets assume you want it to be call "read"
The easiest way is to do following:
edit routes.php as following:
$routes['read/(:num)/(:any)'] = "read/read_it/$1";
line above takes URL as following: server.ufo/read/1/my-super-joke and translates it to this server.ufo/read/read_it/{id}
lets have controller structure as following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Read extends CI_Controller {
public function __construct()
{
parent::__construct();
//Do your magic here
}
public function index()
{
//leave empty or redirect somewhere
}
public function read_it($id = FALSE)
{
if ($id === FALSE) redirect(); //go to default controller
$data['results'] = $this->getjokes_m->readJokes( $id ); //id is NUMERICAL auto incremented value!!
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/read', $data);
$this->load->view('template/footer');
}
}
/* End of file read.php */
/* Location: ./application/controllers/read.php */
and lastly generation of links is simple:
<p class="joke-content"><?php echo $joke; ?></p>
remember joke_id is autoincremented ID, and joke_name is your magic slug (name)
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