Foreach loop shows only few items - php

I'm working with CodeIgniter.
I need to get some data from database with a foreach loop.
I have 4 items in the database, but the loop retrieve only two of them (the items with id 2 and 4).
This is the code in the for the foreach in the controller:
$this->load->model('home_model');
$data['query']=$this->home_model->get_films($limit);
if ($data['query']) {
$data['main_content'] = 'home';
$data['film'] = array();
foreach($data['query'] as $film_info) {
$data['film'] = array(
'id' => $film_info->id,
'poster_src' => $film_info->film_poster_src,
'title' => $film_info->film_name,
'year' => $film_info->film_year,
'genre_id' => $film_info->genre_id,
);
$this->db->select('*');
$this->db->from('genres');
$this->db->where('id', $film_info->genre_id);
$query1 = $this->db->get();
$genre_info = $query1->row();
$data['genre_name'] = $genre_info->genre_name;
$this->db->select('*');
$this->db->from('votes');
$this->db->where('film_id', $film_info->id);
$this->db->where('vote', '1');
$query2 = $this->db->get();
$data['votes_count'] = $query2->num_rows();
}
$this->load->view('template', $data);
This is the code in the model:
<?php
class Home_model extends CI_Model
{
function get_films($limit)
{
$query = $this->db->get('films', $limit, $this->uri->segment(2));
return $query->result();
}
}
And this is the code in the view:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="<?php echo $film['poster_src'] ?>" alt="Film poster">
<div class="caption">
<h3><?php echo $film['title'] ?></h3>
<p>Year: <?php echo $film['year'] ?></p>
<p>Genre: <?php echo $genre_name ?></p>
<p>Votes: <?php echo $votes_count ?></p>
<p>Watch Add to bookmarks</p>
</div>
</div>
</div>
If I put the foreach code in the view, it works properly.

I am not 100% sure so don't vote if false just make me aware i will try another way if possible.in foreach loop try to put the data in another array like this
$new_array[] = $the_result_value_you want
then you will be able to use $new_array outside the loop

Related

How can I get all categories from the database in the header?

I have a header.php in which I have the top navigation. In this nav I have a dropdown menu which gives me all the categories that are in the database table categories(id, category).
Here is the part of the header:
<div class="dropdown">
<button class="dropbtn">
<a
href="http://localhost:8888/blog/public/index.php/categories"
title="Categories">
Categories
</a>
</button>
<div class="dropdown-content">
<?php foreach ($categories as $cat): ?>
<a
href="http://localhost:8888/blog/public/index.php/categories/
<?php echo e($cat['category']); ?>">
<?php echo e($cat->category);?>
</a>
<?php endforeach; ?>
</div>
The next function is in my CategoryRepository.php and gets all Categories from the database:
public function allCategories()
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->query("SELECT * FROM `$table`");
$allCategories = $stmt->fetchAll(PDO::FETCH_CLASS, $model);
return $allCategories;
}
I need this function for the foreach in the navigation, the problem is that I have to put following code:
$categories = $this->categoryRepository->allCategories();
In every function in the Controllers in which a new site for the blog is rendered; here is an example:
public function index()
{
$categories = $this->categoryRepository->allCategories();
$posts = $this->postsRepository->all();
$this->render("post/index", [
'posts' => $posts,
'categories' => $categories,
]);
}
Is there a possibility I'm not forced to put this code row in every function for a new site?
I already tried to put it in the __construct, but somehow it didn't work.
$fields = $this->db->list_fields($table); // gives you category `like(id, category,name)`
then you can manage what you need,
for ($i = 0; $i < count($fields); $i++) {
$fields[$i] = str_replace('_', ' ', $fields[$i]);
`$fields[$i] = ucwords($fields[$i]);`
}
return array('schema' => array_values($fields));

How to retrieve explode images path in database to view in codeigniter 2.2.6

`hi guys am trying from 4 days am not getting . how to retrieve multiple images from using explode functionality.Now I need to explode that image in view . i getting single images from an array but not retrieveing multiple images in my database have one row contains three images how to return result from model.
and show in the view file
myview file:
`<div class="carousel-inner" >
<?php echo $this->session->flashdata('message')?>
<?php $item_class = 'active';
foreach($newzw as $result){?>
<div class="item <?php echo $item_class; ?> ">
<div class="overlay"></div>
<?php $img=explode(",",base_url().'uploads/images/'.$result->image);
//print_r($img);exit;
?>
<img src="<?php echo $img[0] ?> " alt="Los Angeles" style="height:662px;" >
</div>
<?php $item_class = '';
} ?>
</div>
<!-- Left and right controls -->
</div>
</div>
my model code:
function uploadslide1()
{
$this->db->select('*');
$this->db->order_by("id", "DESC");
$query = $this->db->get("sg_slides");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
controller:
function index()
{
$data=$this->general();
$data['newzw']=$this->public_model->uploadslide1();
$data['body']="static/body";
$this->load->view('welcome',$data);
}
I'm just telling you how to using explode.
The explode() function breaks a string into an array. If you want to break your image value into an array format then you have to do this
explode(separator,string); // Syntax
In your case , plays a role of separator.
$img = explode(",", $result->image); //store image value as an array format in img
Now you have the $img variable as an array now you can perform itteration using foreach
example:
foreach($img as $src){
echo '<img src="'.base_url().'uploads/images/'.trim($src)." />';
}

In database table there is no rows means getting error Undefined variable: results using codeigniter

In database table there is no rows means getting error Undefined variable: results using codeigniter,in case there is no row or empty table is there means i want to display view page
controller
$data['breview'] = $this->Profile_model->review();
$this->load->view('supplierreview', $data);
Model
public function review() {
$this->db->select('*');
$this->db->from('reviews');
$this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = reviews.supplier_id');
$this->db->join('customer_registration', 'reviews.customer_id=customer_registration.id');
$this->db->join('sub3_category', 'reviews.product_id=sub3_category.id');
$this->db->where('supplierid_fk', $this->session->id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
view page
<?php
foreach ($breview as $row) {
?>
<div class="reviewsection">
<img src="<?php echo 'data:image;base64,' .$row->product_image; ?>" class="img-circle img-user" alt="" width="50px;" height="50px;"/>
<span class="starfont"><botton class="btn btn-danger"> <?php echo $row->ratings; ?> <span class="fa fa-star starfont"></span></botton> </span>
<div class="content-left">
<p><b>Product Name:<?php echo $row->product_name; ?></b></p>
<p><?php echo $row->review_msg; ?></p>
<?php $buyer_review = strtotime($row->review_date);?>
<?php $date=date('d-F-Y',$buyer_review); ?>
<p>Buyer Name : <?php echo $row->first_name; ?> <?php echo $date ; ?></p>
</div>
</div>
<?php } ?>
$results is not defined.
Please add $results = [];
Here you go:
$results = [];
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
In my model, in most cases, i do the following
public function my_function() {
//$qry = YOUR_QUERY
if ($qry->num_rows() > 0) //or ==1 or whatever, depends on your structure
return $qry->result_array(); // or row_array, depends on your structure
return FALSE;
}
Then in your controller you can check if the result is FALSE or EMPTY like:
$result_from_model = $this->my_model->my_function();
if($result_from_model && !empty($result_from_model)) {
//your code here
}
You can use the following code :
return (is_array($results)?$results:array());
Hope it works.
All the answers given so far are good. Here is yet another way to do it. It's essentially the same as the accepted answer only using a ternary instead of if.
$query = $this->db->get();
return $query->num_rows() > 0 ? $query->result() : array();
}

How to store values of the index in an array?

I have an array that looks like this
Array ( [0] => test1 [1] => test4 [2] => test2 )
I got this value from my database using Codeigniter built-in function
And whenever I try to insert this value back in my database, it's inserting the index instead of the value itself
The error I'm getting is
As you can see, instead of storing test1, test4, test2 in the fields under username, it is storing the index which are 0, 1, 2.
How to fix this please?
References:
#MichaelK
TABLE:
Project Table
User Table
Project-User Table
VIEW
<div class="panel-body">
<?php echo form_open('admin/add_recommended'); ?>
<div class="form-group col-lg-12">
<label>Recommended Employees:</label>
<?php echo form_error('skillsRequired'); ?>
<?php
foreach ($users as $row) {
$user[] = $row->username;
}
print_r($user);
echo form_multiselect('user[]', $user, $user, array('class' => 'chosen-select', 'multiple style' => 'width:100%;'));
?>
</div>
</div>
<div class="panel-footer">
<?php echo form_submit(array('id' => 'success-btn', 'value' => 'Submit', 'class' => 'btn')); ?>
<?php echo form_close(); ?>
</div>
CONTROLLER
public function add_recommended() {
$this->form_validation->set_rules('skillsRequired', 'Skills Required', 'min_length[1]|max_length[55]');
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
$data['users'] = $this->admin_model->getUsers($last_id);
}
$this->load->view('admin/projects/rec-employee', $data);
if ($this->form_validation->run() === FALSE) {
//$this->load->view('admin/projects/rec-employee');
} else {
$users = $this->input->post('user');
print_r($users);
foreach ($users as $user) {
$data = array(
'projectID' => $last_id,
'username' => $user
);
$id = $this->admin_model->insert('projectemp', $data);
}
if ($id) {
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_recommended');
}
}
}
RENDERED VIEW
why you use $data['users'] in controller. Where $users contains index value. You try this
//CONTROLLER
$data = $this->admin_model->getUsers($last_id); //last id is the latest id.
//VIEW
foreach ($data as $row) {
$user[] = $row->username;
}
Boy these are too many comments for a small problem.
First of all #blakcat7, I hope you won't mind If I suggest a little change in your DB Schema. Use indexes and proper normalization it always helps. I have simulated your case on my machine.
It is your user table, I have added an ID with in this table.
Its your project table, just changed some field names, you can use your own
This is your table to create your join, Although you could have used user_id or posted_by field in projects table which could solve your problem too
Now Where i see it, you have users in your database table, you also have added projects but now you want to assign or associate that project with the user.
Make it simple just create a view where you can see both projects and users
Rendered by the Controller function
public function assignProject()
{
$data['projects']=$this->admin_model->getAll('projects');
$data['users']=$this->admin_model->getAll('user');
if($_POST)
{
$this->admin_model->assignUser($_POST);
$data['success']='User Assigned';
$this->load->view('assignProjects',$data);
}
else
{
$this->load->view('assignProjects',$data);
}
}
The view rendered by following markup
<form action="" method="post">
<div class="form-group">
<label>Project</label>
<select name="project" class="form-control">
<?php for($i=0;$i<count($projects);$i++){?>
<option value="<?php echo $projects[$i]['id']?>"><?php echo $projects[$i]['title']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Users</label>
<select name="user" class="form-control">
<?php for($i=0;$i<count($users);$i++){?>
<option value="<?php echo $users[$i]['id']?>"><?php echo $users[$i]['username']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Assing User</button>
</div>
</form>
Just hit Assign User and the following function in the Model will save it in the project-user table
public function assignUser($data)
{
$record=array(
'user_id'=>$data['user'],
'project_id'=>$data['project'],
);
$this->db->insert('user_projects',$record);
}
Remember, always use an Index (ID) field in your tables, would make your DB iteration life simpler
OKAY EVERYONE, THANKS Y'ALL FOR YOUR HELP. IT REALLY MEANS SO MUCH TO ME. AFTER LIKE 2 DAYS OF STRUGGLE I FINALLY FIXED MY PROBLEM. ^_^
Special thanks to Michael K for helping me point out the problem and Malik Mudassar for giving me the idea how to do it.
Controller
public function add_recommended() {
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
}
$data['users'] = $this->admin_model->getUsers($last_id);
$this->load->view('admin/projects/rec-employee', $data);
if ($_POST) {
$users = $this->input->post('recommended');
foreach ($users as $user):
$data = array(
'projectID' => $last_id,
'userID' => $user
);
$id = $this->admin_model->insertRecEmp($data);
endforeach;
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_project');
}
}
Model
public function getUsers($id) {
$this->db->select('*');
$this->db->from('users_skills e');
$this->db->join('projects_skills p', 'e.skillsID = p.skillsID');
$this->db->join('users u', 'u.userID = e.userID');
$this->db->where('p.projectID', $id);
$this->db->group_by('e.userID');
$this->db->order_by('e.percentage', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$result[] = $row;
}
return $result;
}
return false;
}
public function getID() {
$this->db->select_max('projectID');
$this->db->from('projects');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function insertRecEmp() {
$this->db->insert('projects_users', $data);
}
View
<form action="add_recommended" method="post">
<select name="recommended[]" class="chosen-select" multiple title='Select Skills' multiple style="width: 100%;">
<?php for ($i = 0; $i < count($users); $i++) { ?>
<option value="<?php echo $users[$i]->userID ?>"><?php echo $users[$i]->username ?></option>
<?php } ?>
</select>
</form>
I completely changed my database and my PHP function for multi select

Can't update data using Mysql and Codeigniter

i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)

Categories