Codeigniter dropdown only retrieve last data from db - codeigniter

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;
}

Related

Load images from database 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 } ?>

Codeigniter Join Not Displaying Group By Correct

I have this model function below which lets me join both tables. Printed results are at bottom of question.
<?php
class Forum_model extends CI_Model {
public function get_forums() {
$this->db->select('f.*, fc.*');
$this->db->from('forum_category fc', 'left');
$this->db->join('forum f', 'f.forum_id = fc.category_forum_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
}
How ever when I go to look at in on my view it displays it like image below
The two General categories news, lounge should be displayed on the one panel. For some reason it displays the two general categories in own panel.
Question: How is it possiable to display the two categories together? I have tried $this->db->group_by('fc.category_forum_id')
Image
Controller
<?php
class Home extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('reports/thread_analytics_model');
$this->load->model('forum/forum_model');
}
public function index() {
$results = $this->forum_model->get_forums();
echo "<pre>";
print_r($results);
echo "</pre>";
$data['forums'] = array();
foreach ($results as $result) {
$data['forums'][] = array(
'forum_name' => $result['forum_name'],
'category_name' => $result['category_name']
);
}
$data['content'] = 'common/home_view';
$this->load->view('theme/default/template_view', $data);
}
}
View
<?php foreach ($forums as $forum) {?>
<div class="panel panel-home">
<div class="panel-heading"><h1 class="panel-title"><?php echo $forum['forum_name'];?></h1></div>
<div class="panel-body">
<table class="table">
<tbody>
<tr>
<td><?php echo $forum['category_name'];?></td>
</tr>
</tbody>
</table>
</div>
</div><!-- Panel -->
<?php }?>
Printed Results Image
A possible solution with your approach would be:
class Forum_model extends CI_Model {
public function get_forums() {
$arrGroupedData = array();
$this->db->select('f.*, fc.*');
$this->db->from('forum_category fc');
$this->db->join('forum f', 'f.forum_id = fc.category_forum_id', 'left');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach($query->result_array() AS $arrCategory)
{
$arrGroupedData[$arrCategory['forum_id']][] = $arrCategory;
}
return $arrGroupedData;
} else {
return false;
}
}
}
But in my opinion - you should probably split up your queries
1 query to get the forums and 1 query to get all categories from your forums
and stick it together in a tree structure
example for you
$forums = array();
$results = array(
array(
'forum_name' => 'general',
'category_name' => 'news1'
),
array(
'forum_name' => 'general',
'category_name' => 'news2'
),
array(
'forum_name' => 'latter',
'category_name' => 'news3'
),
);
foreach ($results as $result)
{
if(in_array($result['forum_name'],$forums))
{
$array = array($result['category_name']);
array_push($forums[$result['forum_name']],$array);
}
else
{
$forums[$result['forum_name']][] = array(
'forum_name' => $result['forum_name'],
'category_name' => $result['category_name']
);
}
}
echo '<pre>';
print_r($forums);

Fatch value in Dependent dropdown in Yii2

I created a Dependent drop-down now i want to fetch these values on update page. How can i do ?
I created 2 drop-down - 1st Client and 2nd Staff
on update page i got the value of client but i did not get the value of staff (Because it is dependent drop-down)
Form
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists&id=')).'"+$(this).val(), function( data )
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')
->dropDownList
(
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
Controller
public function actionLists($id)
{
$sql = "select * from staff where client='$id' ";
//exit;
$models = Staff::findBySql($sql)->asArray()->all();
//echo "<pre>";print_r($model);exit;
if(sizeof($models) >0){
echo "<option>-Choose a Sub Category-</option>";
foreach($models as $model){
echo "<option value='".$model['id']."'>".$model['fname']."</option>";
}
}
else{
echo "<option>-Choose a Sub Category-</option><option></option>";
}
}
first add $modelsStaff variable to your create and update actions like below:
<?
public function actionCreate()
{
$modelsStaff=null;
$model = new model();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
$sql = "select * from staff where client='$model->client'";
$modelsStaff = Staff::findBySql($sql)->asArray()->all();
return $this->render('update', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
?>
In your update action find all staff using $model->client and get all staff under this client and update your view like this
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists?id=')).'"+$(this).val(), function( data ) //<---
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')->dropDownList
($modelsStaff,
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
You have to create separate function in your controller (like an example):
public function actionLists($id)
{
$posts = \common\models\Post::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if (!empty($posts)) {
$option = '<option>-Select Option-</option>';
foreach($posts as $post) {
$options .= "<option value='".$post->id."'>".$post->title."</option>";
}
return $options;
} else {
return "<option>-</option>";
}
}
and in view file (example):
use yii\helpers\ArrayHelper;
$dataCategory=ArrayHelper::map(\common\models\Category::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'category_id')->dropDownList($dataCategory,
['prompt'=>'-Choose a Category-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('post/lists?id=').'"+$(this).val(), function( data ) {
$( "select#title" ).html( data );
});
']);
$dataPost=ArrayHelper::map(\common\models\Post::find()->asArray()->all(), 'id', 'title');
echo $form->field($model, 'title')
->dropDownList(
$dataPost,
['id'=>'title']
);
This is from Yii docs: https://www.yiiframework.com/wiki/723/creating-a-dependent-dropdown-from-scratch-in-yii2

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 : displaying query result in controller

I am trying to display my db query result in my controller, but I don't know how to do it. could you please show me?
Controller
function get_name($id){
$this->load->model('mod_names');
$data['records']=$this->mod_names->profile($id);
// I want to display the the query result here
// like this: echo $row ['full_name'];
}
My Model
function profile($id)
{
$this->db->select('*');
$this->db->from('names');
$this->db->where('id', $id);
$query = $this->db->get();
if ($query->num_rows() > 0)
{ return $query->row_array();
}
else {return NULL;}
}
echo '<pre>';
print_r($data['records']);
or
echo $data['records'][0]['fullname'];
Model:
function profile($id){
return $this->db->
select('*')->
from('names')->
where('id', $id)->
get()->row_array();
}
Controller:
function get_name($id){
$this->load->model('mod_names');
$data['records']=$this->mod_names->profile($id);
print_r($data['records']); //All
echo $data['records']['full_name']; // Field name full_name
}
You do that inside a View, like this.
Controller:
function get_name($id){
$this->load->model('mod_names');
$data['records']=$this->mod_names->profile($id);
$this->load->view('mod_names_view', $data); // load the view with the $data variable
}
View (mod_names_view):
<?php foreach($records->result() as $record): ?>
<?php echo $record->full_name); ?>
<?php endforeach; ?>
I would modify your model then to something like this (it worked for me):
function profile($id)
{
$this->db->select('*');
$this->db->from('names');
$this->db->where('id', $id);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query; // just return $query
}
}

Resources