Load images from database CodeIgniter - codeigniter

I would like to create a photo gallery, taking images from the database.
I'm using codeigniter.
Database
this is a static page located in views/pages/gallery.php
does anyone have any ideas?

What you want is to query the database table, get the relevant fields, and return that to a view. In MVC, it looks something like this:
Model:
class Portfolio_model extends CI_Model {
public function get_items() {
$this->db->select('name, description, image');
$this->db->order_by('date', 'DESC');
$q = $this->db->get('tablename'); // your tablename here
if ($q->num_rows() > 0) {
return $q->result();
} else {
return null;
}
}
}
Controller:
class Portfolio extends CI_Controller {
public function index() {
$this->load->helper('html');
$this->load->model('portfolio_model');
$data['items'] = $this->portfolio_model->get_items();
$this->load->view('portfolio', $data);
}
}
View:
if (!is_null($items)) {
foreach ($items as $item) {
echo $item->name . '<br>';
echo $item->description . '<br>';
echo 'Image src: ' . base_url() . $item->image . '<br>'; // might need slash after base_url, don't remember
echo img($item->image);
}
} else {
echo 'No items found!';
}

This worked for me :
Controller -
public function index(){
$this->load->model('galleryModel');
$data1['items'] = $this->galleryModel->get_items();
$this->load->view('gallery', $data1);
}
Model -
public function get_items() {
$this->db->select('*');
$this->db->from('gallery');
$query = $this->db->get();
if($query->num_rows() != 0){
return $query->result_array();
}else{
return false;
}
}
View -
<?php
foreach ($items as $item) {
$image_id = $item['image_id'];
$name = $item['name'];
$category = $item['category'];
$image = $item['image'];
?>
<div class="tile scale-anm <?php echo $category; ?>">
<img src="<?php echo $image; ?>" class="film-img-gallery" alt="" />
</div>
<?php } ?>

Related

Display Categories and subcategories using CodeIgniter

I have two table in my database, One is Categories and the other is Sub_Categories, I want to display them like this:
Categorie 1
sub categoie 1
sub categoie 2
sub categoie 3
sub categoie 4
Categorie 2
sub categoie 1
sub categoie 2
sub categoie 3
sub categoie 4
But i don't know how to do this.
In my Database table i have this fields :
Categories: ID, Name, Icon.
Sub_Categories: ID, Categ_id, Name
This should work;
public function get_categories()
{
$query = $this->db->get('Categories');
$return = array();
foreach ($query->result() as $category)
{
$return[$category->id] = $category;
$return[$category->id]->subs = $this->get_sub_categories($category->id); // Get the categories sub categories
}
return $return;
}
public function get_sub_categories($category_id)
{
$this->db->where('Category', $category_id);
$query = $this->db->get('Sub_Categories');
return $query->result();
}
All this does is get's all the categories, but then gets all the subcategories for each of the categories. Calling the get_categories() function should return an object in the format you want.
I hope this helps.
Edit
You would call the get_categories function from your controller and pass it to the view;
$data['categories'] = $this->your_model->get_categories();
$this->load->view('view_file', $data);
Then within your view you would display them like this;
<ul>
<?php
foreach ($categories as $category)
{
?>
<li><?php echo $category->name; ?>
<?php
if(!empty($category->subs)) {
echo '<ul>';
foreach ($category->subs as $sub) {
echo '<li>' . $sub->name . '</li>';
}
echo '</ul>';
}
?>
</li>
<?php
}
?>
</ul>
Database
image for database table
Try this
in Model
public function getCategories()
{
$query = $this->db->query('select * from categories where cat_parent=0');
return $query->result_array();
}
public function getCategoriesSub($parent)
{
$query = $this->db->query("select * from categories where cat_parent='$parent'");
return $query->result_array();
}
in Controller
public function categories()
{
$data['mcats'] = $this->admin_model->getCategories();
foreach($data['mcats'] as $key =>$val){
$subcats = $this->admin_model->getCategoriesSub($val['cid']);
if($subcats){
$data['scats'][$val['cid']] = $subcats;
}
}
$this->load->view('admin/header');
$this->load->view('admin/category_list', $data);
$this->load->view('admin/footer');
}
In view
<ul>
<?php
foreach ($mcats as $key =>$val)
{
?>
<li><?php echo $val['cat_name']; ?>
<ul>
<?php
foreach ($scats[$val['cid']] as $sub) {
echo '<li>' . $sub['cat_name'] . '</li>';
}
?>
</ul>
</li>
<?php
}
?>
</ul>
its already working code - i think it is usefull

Codeigniter dropdown only retrieve last data from db

I use CI form with form_dropdown helper and tried to pull Mysql data into its options, from the below code, its only retrieve the last record from db into the option list?
please advise what is wrong with my code?
Model
public function getStates() {
$query = $this->db->get('states');
$return = array();
if($query->num_rows() > 0){
$return[''] = 'please select';
foreach($query->result_array() as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}
Controller
$this->load->model('db_model');
$data['options'] = $this->db_model->getStates();
$this->load->view('create_new', $data);
View
$state = array(
'name' => 'state',
'id' => 'state',
//'value' => set_value('state', $state)
);
<?php echo form_label('State', $state['id']); ?>
<?php echo form_dropdown($state['name'], $options); ?>
<?php echo form_error($state['name']); ?>
<?php echo isset($errors[$state['name']])?$errors[$state['name']]:''; ?>
send full query result from the model to the view like this
Model
public function getStates() {
$query = $this->db->get('states');
return $query->result();
}
let the controller as it is and now you can populate states in dropdown like this:
View
<?php
foreach($options as $opt){
$options[$opt->state_id]=$opt->state_name;
}
echo form_dropdown($state['name'], $options);
?>
Try this:
function getStates() {
$return = array();
$query = $this->db->get('states')->result_array();
if( is_array( $query ) && count( $query ) > 0 ){
$return[''] = 'please select';
foreach($query as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}

codeigniter how to show data in functions

My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

passing multiple queries to view with codeigniter

I am trying to build a forum with Codeigniter.
So far i have the forums themselves displayed and the threads displayed, based on the creating dynamic news tutorial.
But that is 2 different pages, i need to obviously display them into one page, like this:
Forum 1
- thread 1
- thread 2
- thread 3
Forum 2
- thread 1
- thread 2
etc.
And then the next step is obviously to display all the posts in a thread. Most likely with some pagination going on. But that is for later.
For now i have the forum controller (slimmed version):
<?php
class Forum extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('forum_model');
$this->lang->load('forum');
$this->lang->load('dutch');
}
public function index()
{
$data['forums'] = $this->forum_model->get_forums();
$data['title'] = $this->lang->line('title');
$data['view'] = $this->lang->line('view');
$this->load->view('templates/header', $data);
$this->load->view('forum/index', $data);
$this->load->view('templates/footer');
}
public function view($slug)
{
$data['forum_item'] = $this->forum_model->get_forums($slug);
if (empty($data['forum_item']))
{
show_404();
}
$data['title'] = $data['forum_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('forum/view', $data);
$this->load->view('templates/footer');
}
}
?>
And the forum_model (also slimmed down)
<?php
class Forum_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
public function get_threads($forumid, $limit, $offset)
{
$query = $this->db->get_where('thread', array('forumid', $forumid), $limit, $offset);
return $query->result_array();
}
}
?>
And the view file
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<p><?=$view?></p>
<?php endforeach ?>
Now that last one, i would like to have something like this:
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<?php foreach ($threads as $thread_item): ?>
<h2><?php echo $thread_item['title'] ?></h2>
<p><?=$view?></p>
<?php endforeach ?>
<?php endforeach ?>
But the question is, how do i get the model to return like a double query to the view, so that it contains both the forums and the threads within each forum.
I tried to make a foreach loop in the get_forum function, but when i do this:
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
foreach ($query->row_array() as $forum_item)
{
$thread_query=$this->get_threads($forum_item->forumid, 50, 0);
}
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
i get the error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/forum_model.php
Line Number: 16
I hope anyone has some good tips, thanks!
Lenny
*EDIT***
Thanks for the feedback.
I have been puzzling and this seems to work now :)
$query= $this->db->get('forum');
foreach ($query->result() as $forum_item)
{
$forum[$forum_item->forumid]['title']=$forum_item->title;
$thread_query=$this->db->get_where('thread', array('forumid' => $forum_item->forumid), 20, 0);
foreach ($thread_query->result() as $thread_item)
{
$forum[$forum_item->forumid]['thread'][]=$thread_item->title;
}
}
return $forum;
}
What is now next, is how to display this multidimensional array in the view, with foreach statements....
Any suggestions ?
Thanks
You are using row_array() hence your error, change your get_forums() to:
$thread_query=$this->get_threads($forum_item['forumid'], 50, 0);
But I believe you should actually be using result_array() since you want a list of all forums.

Resources