Codeigniter: passing data to another view - php

Ok, so this question may be very simple and I'm just missing something basic but here goes. My website I'm currently building is developed in Codeigniter. It's a site for exercises.
Now one of my functions (biceps) calls a model (model_get) that grabs data from my database and then passes it into a view (content_biceps.php)
So to try and explain this best as possible here is my controller model and view for this.
Controller function:
public function biceps(){
if($this->session->userdata("is_logged_in")){
$this->load->model("model_get");
$data["results"] = $this->model_get->getExercises("1");
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("site_sidebar");
$this->load->view("content_biceps", $data);
$this->load->view("site_footer");
} else {
redirect ("site/restricted");
}
}
Model function get_data:
function getData($page){
$query = $this->db->get_where("pagedata", array("page" => $page));
return $query->result();
}
View content_biceps:
foreach($results as $row){
echo '<div class="item">
<h2>'.$row->name.'</h2>
<img src="'.$row->image.'" alt="'.$row->name.'" />';
$e_id = $row->e_id;
echo $e_id;
echo form_submit('exercise_submit', 'view');
echo '</div>';
echo form_close();
}
Now this view works great, it grabs the data i need such as the name, image and e_id for each exercise and displays them all.
If you notice the submit button named 'view'. If you can imagine all of these exercises displayed on one page. They all have a unique e_id. I want it so that when i click the view button on a certain exercise, i am taken to a page view such as 'exercise_view' where i can use the e_id to grab the data for that particular exercise. At the moment I dont know how to take the e_id when i click view and use it in another page.
Any help would be great.

You can try to add an input with the e_id you want, for example
<div>
<input type="hidden" name="e_id" value="{$e_id}" />
<input type="submit" name="view" />
</div>
then in controller, you can get the e_id
$e_id = $this->input->post('e_id');

Related

How can I pass input value from view to controller and model to fetch data correctly? Codeigniter

I am trying to fetch a data that has the same id of my input hidden value.
I cannot fetch the id or input hidden value of the data
To start with, this is what I've done to make things clearer for me to debug things I made a hard coded form and a button to bring me to the page
In View - groups/index.php
As you can see I made the posts/index/1 which is a hard coded value but I can change that later easily that is not my problem
<?php echo form_open('posts/index/1') ?>
<input type="hidden" name="txtGroup" value="1" />
<button type="submit" class="btn btn-info"> Submit</button>
</form>
So after I made the form I will make a function in controller to fetch the posts/index
In Controller - Posts.php
public function index(){
$this->load->view('templates/header');
$this->load->view('teachers/posts/index');
$this->load->view('templates/footer');
}
And so I fetched the page. At this point, i can now go through /posts/index/1 and see my page
In my page posts/index.php I have a data and it is fetched through Ajax here it is
So I already fetched this data in posts/showPosts
showAllQuestions();
//Show all data
function showAllQuestions(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>posts/showPosts',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
var n=1;
for(i=0; i<data.length; i++){
html +='<div class="card">'+
'<div class="card-header" style="color:white; background-color:black">'+
'<h4><span class="iconify" data-icon="ant-design:info-circle-outlined" data-inline="false"></span> Question No. '+ n++ +'</h4>'+
'</div>'+
'<div class="card-body">'+
'<form>'+
'<div class="form-group">'+
'<label for="exampleFormControlTextarea1"><h5> <span class="iconify" data-icon="emojione:check-mark-button" data-inline="false"></span> </h5></label>'+
'<input type="text" value="'+data[i].question+'" class="form-control" disabled />'+
'</div>'+
'<hr>'+
'<span class="iconify" data-icon="el:edit" data-inline="false"></span> '+
'<span class="iconify" data-icon="fa-solid:trash-alt" data-inline="false"></span>'+
// 'Edit '+
'</form>'+
'</div>'+
'</div><br>';
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
In posts/showPosts - Posts.php, this is the controller
public function showPosts(){
$result = $this->post_model->showPosts();
echo json_encode($result);
}
Finally the Model to Determine if I fetched the correct ID depending on the data id I submit
Problem is the $id is null and I don't have a clue to start with, because I declare a hidden input value on the view page.
public function showPosts(){
// Show questions and answers
$id = $this->input->post('txtGroup');
$this->db->select('*');
$this->db->from('questions');
$this->db->where('group_id', $id);
$query = $this->db->get();
return $result = $query->result_array();
}
I am going to try to understand this question better than your previous one (which is now safe to delete since this is a better description of your issue).
In your groups/index.php view, you want to allow a user to navigate to the posts/index page and pass an integer as a single parameter (which is hard-coded by you, not entered by the user) -- I'll refer to it as $txtGroup for context. Because you are not performing a INSERT|UPDATE|DELETE operation, better practice is to send the data as a $_GET instead of $_POST. Because Codeigniter enables the passing of $_GET parameter as a slash-delimited extension of the url, I don't see any benefit in setting up a <form>.
Style your new hyperlink as a button using your preferred classes.
Link to <?php echo $integer; ?>
This will send your data to the posts/index.php controller. This is where you should be accessing/extracting the $txtGroup value from the url.
Here's where I start to get foggy about what you need. If you want to pass the value to the teachers/posts/index view, then do so by passing an associative array as the second parameter when you load the view.
public function index($txtGroup) {
$this->load->view('templates/header');
// if you want to pass the value to THIS
$this->load->view('teachers/posts/index', ['txtGroup' => $txtGroup]);
$this->load->view('templates/footer');
}
If you are not interested in passing the $txtGroup to the view, then the only other reason to pass the value from groups/index.php to posts/index would be to modify a query and then pass dynamic data to the teachers/posts/index view (which you would need to supply when loading the view anyhow).
public function index($txtGroup) {
$data['posts'] = $this->post_model->showPosts($txtGroup);
$this->load->view('templates/header');
$this->load->view('teachers/posts/index', $data);
$this->load->view('templates/footer');
}
In your model, use the passed argument.
public function showPosts($groupId) {
return $this->db->get_where('questions', ['group_id' => $groupId])->result_array();
}
This way, you don't need to use an ajax call (which looks like you are unconditionally triggering in your view anyhow). Now Codeigniter will work its magic to transfer $data to your view whereby you can access the multidimensional result set as $posts (the variable is named by the first-level key that you assign it). Use a foreach() loop to iterate the rows of results and generate your html content -- all using server-side language.
<?php foreach ($posts as $index => $post) { ?>
<div class="card">
// ... the rest of your content ...
<?php } ?>
As you design the new dynamic content using the above loop:
Use $index as your counter so that you don't have to manually increment.
DO NOT allow INSERT|UPDATE|DELETE operations to be triggered by $_GET events, this is not best practice. Those types of actions should only be initiated by $_POST submissions.

undefined variable on codeigniter

I have a project in which is develop in codeigniter.
The project is like this:
-root
--controller
---Slider.php
--models
---My_data.php
--views
---slider_view.php
---giris.php
Slider.php
public function manset_al(){
$title['title']='manşet listesi';
$this->load->model('My_data');
$data['manset']= $this->My_data->get_manset();
$this->load->view('slider_view' ,$data);
}
My_data.php code is;
public function get_manset() {
// $sorgu =
// mysql_query("select * from manset, haberler
// where manset.onay='1' and manset.link=haberler.id and haberler.onay='1'
// order by haberler.id desc");
$this->db->select('*');
$this->db->from('manset as man, haberler as hab');
$this->db->where('man.link=hab.id');
$this->db->where('hab.onay=1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return $query->result();
}
slider_view.php code is:
foreach($manset as $row){
$baslik =$row->baslik;
$icerik =$row->icerik;
$link =$row->link;
$img_path =$row->img_path;
$giris =$row->giris;
$cikis =$row->cikis;
echo '
<div>
<img data-u="image" src="'.$img_path.'"/>
<div data-u="thumb"> <h5 style="color:white; margin:10px;">'.$baslik.' </h5> </div>
</div>';
}
Now when i called
http//example.com/index.php/Slider/manset_al
every think is ok - the slider is running.
But when i get the slider in giris.php with this code;
$this->load->view('slider_view');
it's not run and say: undefined variable manset;
how can ı fix it?
Thank you.
We're missing some details to quickly solve this one: namely, how is giris.php called, exactly? Without those details I can only give a general answer.
This error means that you are trying to access data in your template file that you haven't passed to the templating system. For instance, in your controller (Slider.php) you pass data off to the templates here:
$this->load->view('slider_view' ,$data);
The $data is the important part: codeigniter takes every entry in that array and creates a variable in the template system whos name corresponds to the name of each key. Therefore, foreach( $manset as $row ) works because $data has a key named manset that has each row in it. You can see that in giris.php you are specifically not sending any data to the template:
$this->load->view('slider_view');
Notice the lack of a second parameter. Of course your file structure implies that giris.php is itself a view file, which means that whatever controller method that called giris.php needs to be the one sending data out to the view. So generally, that is the answer: whatever controller is ultimately calling giris.php needs to be sending the slider information out to the templating system, but isn't. Without more details on how giris.php is actually called, that is as specific as I can get.

attempting to modify a field in codeigniter application db table but know how to identify the table

I am beginner in code igniter php framework. Today I have a task to modify existing code and somehow I am lost in the middle of the line on attempting to located a database table. This is the controller snippet that renders the view
..........
$data["all_types"] = $this->data_model->get_data("all_types",300,"Asc");
$this->load->view("preview_brands",$data);
...........
when the view is loaded I am iterating through the in the view to load data as shown
<div class="decoration"></div>
<?php foreach($all_types as $item): ?>
<div style="display:block;color:#000;">
<a style="font-size:17px;margin:15px 2px;font-family:Cgothic;"
href="<?php echo site_url()."...../..../".$item["id"]; ?>"
class="scale-hover"
title="<?php echo str_replace("_"," ",$item["name"]);?>">
<strong><?php echo str_replace("_"," ",$item["name"]);?></strong>
</a>
</div>
<?php endforeach; ?>
this is the model snippet code as shown
function get_data($db,$i,$order)
{
$this->db->order_by("name",$order);
$this->db->where('consent',"yes");
$query=$this->db->get($db);
return $query->result_array();
}
My challenge is how can I locate or identify the database table the above model is pointing to to fetch data. Hoping someone assists me
all_types is your table name.
$this->db->get($your_table name), get method take table name as a parameter.
Get Method Documentation
If more help needed I'm happy to help.
Happy Coding.
From your model code:
$query=$this->db->get($db);
This means $db is the table name. Looking at your controller code which calls the model function:
$data["all_types"] = $this->data_model->get_data("all_types",300,"Asc");
I can say that all_types is the name of the table.

Show data from another table with modal - Codeigniter

i have 2 tables
Now when i click detail , i want to show data from table 2 which have reportcode as i click on table 1 (image 1)
And now i want to show it on modal , so here is the example
1) click detail button -> get reportcode -> show reimbursename,etc to modal
Can you explain to me what should i do first ? and can you suggest me a plan please ,any answers will be appreciated. Thanks
My suggestion is:
1 - Add one class to detail button, i.e: detailButton and a data attribute or href with the especific reportCode.
<table>
<tr>
<td> ... </td>
<td> <button class='detailButton' href='<?php echo $reportCode; ?>' ... </button> </td>
2 - Add jquery to the bottom of the page:
$('.detailButton').click(function(e){
e.preventDefault();
var reportCode = $(this).attr('href');
var url = "yourUrl/controller/function";
$.post(url,{ code:reportCode },function(data){
//do stuff
//i.e: $('.modal').html(data).show();
});
});
Now you have a function that gets the reportCode, sends it to your controller by POST, you return something and the function gets the response and attach to a html.
Note, this way you must return a table from your controller. You could build dinamically too.
Hope it helps!
UPDATE:
You could check the values to your model and then use a exisitin template (for example one that generates the detail table), and return to your view as data to be attached at the correct position (method 1):
function detail(){
$getcode= $this->input->post('reportCode');
$data['showdetail'] = $this->model_expreport->showdetail($getcode);
$ret = $this->load->view('detail_template',$data,true); //return as data
print_r($ret);
}
Or you could use the Method 2:
function detail(){
$getcode= $this->input->post('reportCode');
$data['showdetail'] = $this->model_expreport->showdetail($getcode);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
}
This way, the view will recive a JSON that you could iterate and build your own page. Or you could create the full view and return it as data (in order to only append to your view).
You could use both.
In the view, you will recive either a full view:
$.post(url,{ code:reportCode },function(data){
$('#modal').html(data); //put the 'detail' response to the modal
}
Or with JSON you must iterate and build your own div dinamically, there are a lot of tutorials for this: https://uno-de-piera.com/cargar-json-con-jquery-y-codeigniter/

How to get the content of current page by passing id from page link to controller

I am working in Codeigniter.
Here is my code which I have written so far to achieve what I am thinking.
View:
<li><a href=" echo $menu->url.'/'.$menu->id " >Gallery</a></li>
Controller:
function view($id){
$content['content'] = $this->MyModel->getContent($id);
$data['header'] = $this->load->view('header', '', true);
$data['content'] = $this->load->view('content', $content, true);
$this->load->view('main_view', $data);
}
Model
function getContent($id){
$this->db->select('page_title, content');
$this->db->from('admin_pages');
$this->db->where('id', $id);
............
return $query;
}
Route
$route['view/(:any)'] = 'mycontroller/view/$1';
What I want to achieve here is, when I click the link in the "View" then it should show me another page with the content of that specific link fetched from the "admin_pages" table based on the parameter "$id" passed to it from the url.
However when I click the link it gives me page not found error.
Any kind of help will be much appreciated.
After trial and error, I found a workaround which I want to share for future references if made.
I changed the link as:
View
<li><a href=" echo base_url().'page/'. $menu->id; " >Gallery</a></li>
Then in the route I changed:
Route
$route['page/(:any)'] = 'mycontroller/view/$1';
What this means is, whenever there in the URL is base_url/page followed by an "id" then it will be remapped or taken to the "view" method in the controller "mycontroller" and the id will be passed as a parameter to the method, which the method will recieve as $id in its definition.

Categories