I'm building a codeigniter site and I have a database table of books - one record for each book with title, author, etc etc fields. I know how to get the db table contents and pass an object to the view and then do a foreach loop to get the values. I could print a table of all the data. However I then get a bit muddled. The page has areas for each book and the data for a book will be one row of the data array. So what I want to do is, if the author is 'this' value, find the correct row in which the author appears and then get the other fields. How can I do a foreach loop that finds the one row with the author's name?
I can't think how to do it - I seem to go round and round in circles.
Help!
Edit: Code:
OK so here's the controller method:
public function index()
{
$books = $this->Books_model->getbooks();
$data = array(
'body_id'=>'home',
'main'=>'home_view',
'books'=>$books
);
$this->load->view('templates/template_main_view', $data);
}
and here's the model method:
function getbooks(){
$query = $this->db->get('books');
return $query->result();
}
so I end up with the variable $books (which is of course an object, not an array) in the view and a var_dump() shows that it has all the data. So far so good. I can then use a foreach loop to get values.
Now I want to extract a single row/record conditional on the fact that it has a given value for 'author' and assign each field of that row to a variable that I can use them in the view. And then I want to repeat that for the other rows. I can't seem to work out how to do that.
Afternote:
I found a way of doing this but not sure if it's the best or neatest:
I do this:
if(isset($books)){
foreach($books as $row){
if($row->author == 'authorname'){
$title = $row->title;
}
}
}
it works but seems a bit clumsy/overkill??
How about creating a specific function for getting the book/s that matches the author name?
For example:
In your controller you can do something like this:
public function index()
{
$data['books'] = $this->Books_model->get_each_book();
$data = array(
'body_id'=>'home',
'main'=>'home_view',
'books'=>$books
);
$this->load->view('templates/template_main_view', $data);
}
The in your model, do something like this:
function get_each_book(){
$this->db->where('author','authorname');
$query = $this->db->get('books');
return $query->result_array();
}
This way, you are gonna filter the results in the model already.
Then in your view, access the variable 'books' through a foreach loop:
Example:
foreach($books as $row)
{
$title = $row['title'];
echo $title;
}
Related
In Controller,
public function detail($id)
{
$item = Item::find($id);
return view('frontend.detail',compact('item'));
}
In blade,
{{$item->subcategory->items}} //question //this code print all the items//
You need to select the items manually if you don't want to fetch the id
Currently, you are fetching all the items by using $item = Item::find($id); it means that fetch all the fields of the particular table againt the given id.
you can use below query by modifying you required fields
Item::select('name','surname')->where('id', 1)->get();
You Need to make hidden id of the column in query Example
Item::find($id)->makeHidden(['id']);
return view('frontend.detail',compact('item'));
I am stuck in getting a value from model and process it in controller. I am new to codeigniter. My model code is this:
public function display_cat_courses($value)
{
$this->db->select('*');
$this->db->from('courses_tbl');
$this->db->join('course_category_tbl', 'courses_tbl.course_category_id = course_category_tbl.id');
$this->db->where('course_category_id', $value);
$query = $this->db->get();
return $query->result();
}
And my controller is this:
public function view()
{
$this->load->model('Category_model');
$cat_id = $this->uri->segment(3);
$data['category']=$this->Category_model->display_cat_courses($cat_id);
}
I just want to get a column value from course_category_tbl and store that inside an array as array element to process that later.Model works fine but in my controller I want to store "course_type" which is a column in course_category_tbl. How to get it.
As you are succesfully getting all datas in array format from model in controller and you only want one field data from array that you need to use for some purpose.For that,you can make use of
$field_values_array = array_column($whole_array, 'field_name');
print_r($field_values_array );
From this code,you will get all values of that column field in array Format,and later you can pass it to view for further proccessing.
You can select required column only:
$this->db->select('course_category_tbl.course_type');
If there is only one row that you'll get by passing the category ID then in the model in place of $query = $this->db->get(); you can add put
$this->db->row_array() and this will give you a one dimensional array and then from the result $query you can access the desired elemnt by passign the index.
E.g
$query['course_type'] will give you course type
I want to grab one field of database from an array that contains all the data fields here is m code:
public function show($id)
{
$data['product'] = $this->products_model->get_product_by_id($id);
foreach ($data['product'] as $row) {
$seller = $row['seller_id'];
}
$data['seller_name'] = $this->members_model->get_members_by_id($seller);
if (empty($data['product']))
{
show_404();
}
$data['main_content'] = 'pages/show';
$this->load->view('templates/template', $data);
}
I think the code is self explanatory what I want is to grab the seller_id field from the products database to use it to grab seller_name field from members database. The code that I thinks it's not working is this part:
foreach ($data['product'] as $row) {
$seller = $row['seller_id'];
}
It gives me this error:
Severity: Notice
Message: Array to string conversion
Severity: Notice
Message: Array to string conversion
This message means that you are getting an array and you are considering it as string as you are passing it like string.
So here is condition ,either you are getting multiple values in $data['product'] and yes that is correct because you are applying foreach there.So make your query in such a way that it will return only one row from products table.that will be solution
You don't need foreach loop, just check if !empty($data['product']) and use $data['product']['seler_id'] or $data['product'][0]['seller_id'] depends how is your model code. So, as you want exact product by id your code should looks like:
public function show($id)
{
$data['product'] = $this->products_model->get_product_by_id($id);
if (empty($data['product']))
{
show_404();
}
else
{
$seller_id = $data['product']['seller_id'];
$data['seller_name'] = $this->members_model->get_members_by_id($seller);
$data['main_content'] = 'pages/show';
$this->load->view('templates/template', $data);
}
}
One notice here, since you have relations between tables, query in model should contain JOIN section and you would be able get seller details in one query. Basically, your $data['product'] would contain name (and other details from sellers table) in same time or in one query. Check this link.
use array_column to get all seller_id's in one array. just like var_dump array_column ( $data, 'seller_id' ) .
Sorry guys the problem was with the view page, That's how I used the array in the view page and it did work:
foreach($seller_name as $row){
echo'<p class="product-price">'.$row['user_name'].'</p>';
echo'<p class="product-price">'.$row["phone_number"].'</p>';
}
I'm trying to fetch certain values from and then pass it to another model in the same control.
However I'm only able to display the last row in the view.
I have shared my code below and I'm not sure where I'm going wrong.
Controller:
public function test($id){
$mapping_details = $this->queue_model->get_mapping_details($id);
foreach ($mapping_details as $value) {
$data['agent_details'] = array($this->agent_model->get_agent_details($value['user_id']));
}
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Model:
public function get_agent_details($id) {
$query = "select * from user_table where id = ".$id." and company_id = ".$this->session->userdata('user_comp_id');
$res = $this->db->query($query);
return $res->result_array();
}
Welcome to StackOverflow. The problem is the iteration in your controller. You are iterating through the $mapping_details results and per every iteration you are re-assigning the value to $data['agent_details'] , thus losing the last stored information. What you need to do is push to an array, like this:
foreach ($mapping_details as $value) {
$data['agent_details'][] = $this->agent_model->get_agent_details($value['user_id']);
}
However, wouldn't it be best if you created a query that uses JOIN to get the related information from the database? This will be a more efficient way of creating your query, and will stop you from iterating and calling that get_agent_details() over and over again. Think of speed. To do this, you would create a model method that looks something like this (this is just an example):
public function get_mapping_details_with_users($id){
$this->db->select('*');
$this->db->from('mapping_details_table as m');
$this->db->join('user_table as u', 'u.id=m.user_id');
$this->db->where('m.id', $id);
$this->db->where('u.company_id', $this->session->userdata('user_comp_id'));
return $this->db->get()->result();
}
Then your controller will only need to get that model result and send it to the view:
public function test($id){
$data['details_w_users'] = $this->queue_model->get_mapping_details_with_users($id);
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Hope this helps. :)
i have a page that shows all student profiles with their results. all the user info i putted in the table "user"
and then i have another table "results" that shows all the students their scores from diffrent courses. the thing is i don't know how to write the query or controller function to link the student with their corresponding results. I need some help here thanks
Controller
function students()
{
$data = array();
$this->load->model('kdg_model');
$query = $this->kdg_model->get_students();
$query2 = $this->kdg_model->get_resultStudent();
if ($query)
{
$data['user'] = $query;
$data['results'] = $query2;
}
$this->load->view('students_view',$data);
}
Model
get_students get all rows from the database table user.
get_resultstudent gets all the rows from results. tried to combine them but it just gives me all the same rows back on every profile.
function get_students(){
$this->db->where('admin', 0);
$query = $this->db->get('user');
return $query->result();
}
function get_resultStudent(){
$this->db->select('*');
$this->db->from('results');
$this->db->join('user', 'user.id_user = results.FK_student');
$query = $this->db->get();
return $query->result();
}
I'm not sure what your database schema looks like but from what I can work out I've got this. Okay so in your controller you want to build your array of students. Let do this by calling two model functions. The first model function we are going to call we get us all of the students in the 'user' table. The model will pass back an array to the controller which we can loop through to get the individual students. On each iteration of the loop we can pass the 'id_user' to another function in our model to get the results for that student.
//This is where we will store the students and their results
$aData['aStudentResults'] = array();
//Load the model we need
$this->load->model('kdg_model');
//Get an array of students
$aStudents = $this->kdg_model->get_students();
//Now we have an array of student id's let loop through these and for each student
//let get their results
foreach($aStudents as $student)
{
//Add the student to the array
//The student id (id_user) is the key
$aData['aStudentResults'][$student->id_user] = $this->kdg_model->get_resultStudent($student->id_user);
}
//Pass out array of students to the view
$this->load->view('students_view', $aData);
These are the model functions we are calling in the controller
//Get all the students that are not admins
function get_students(){
$this->select('id_user')
-from('user')
->where('admin', 0);
$query = $this->db->get();
return $query->result();
}
//Use the id_user we were passed by the controller to get the results
function get_resultStudent($id_user){
$this->db->select('*');
$this->db->from('results');
$this->db->where('FK_student', $id_user);
$query = $this->db->get();
return $query->result_array();
}
At this point we now have all the data we need. We just need to pass it from the controlle to the view which we did by passing the view $aData. In our view we can access what we passed to it like so
<? foreach($aStudentResults as $studentId => $aResults): ?>
<p>Student id: <?= $studentId ?></p>
<?foreach($aResults as $aResult): ?>
//Do something with results
<? endforeach; ?>
<? endforeach; ?>
This hasn't been tested so there may be some syntax errors but hopefully you should get an idea of what I am trying to do and what you need to do.
It's important for you to understand how MVC works. Practice selected data from your database in your models, and then passing that data to your views via the controller. You'll quickly get the hang of it.
If there is anything you don't understand in this answer please leave a comment and let me know.