passing the input name (comes from database) from view to controller - php

I'm trying to learn codeigniter, the first thing i did is to make simple add edit delete function...
I'm having trouble calling the name of input button to the controller to delete an entire row of table..
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Delete_model extends CI_Model{
public function delete($data){
$this->db->delete('record_tbl', $data);
}
}
controller
class Delete_controller extends CI_Controller {
public function index()
{
$this->delete();
}
public function delete()
{
$data = array();
$this->load->model('fetch');
$query = $this->fetch->getData();
if ($query)
{
$data['results'] = $query;
}
$this->load->view('delete', $data);
}
public function delete_data(){
$this->load->model('delete_model');
$where = $this->input->get('id');
$data['id'] = $where;
$this->delete_model->delete($data);
redirect('');
}
}
view
<table border="1" width="100%">
<tr>
<th>Name</th>
<th>Address</th>
<th>Phone Number</th>
<th>Status</th>
<th></th>
</tr>
<?php foreach($results as $row) { ?>
<tr>
<td><?=$row->name?></td>
<td><?=$row->addr?></td>
<td><?=$row->pnum?></td>
<td><?=$row->status?></td>
<?php echo form_open('delete_controller/delete_data') ?>
<td style="text-align: center"><input name="<?=$row->id?>" type="submit" value="delete"></input>
</form>
</td>
</tr>
<?php } ?>
</table>

Your form will be doing a POST rather than a GET request. So rather than doing
$where = $this->input->get('id');
You want to do
$where = $this->input->post('id');
Also why don't you pass the value of $row->id to your controller so that you know which input field to target. So in your view do
<?php echo form_open('delete_controller/delete_data/' . $row->id) ?>
Then in your controller
public function delete_data($id){
$this->load->model('delete_model');
$where = $this->input->post($id);
//...

It's going to be $this->input->post ('id') like #Pattle says and you are using the "name" attribute of the form for the ID. What I usually do is use a hidden field (see form_hidden () helper in CI documentation) with the name "id" and the value you want ($row->id).
<?php echo form_hidden ('id', $row->id); ?>

Instead of $this->input->get('id'); use $this->input->post('id');.
And to simplify things up: I probably recommend using <button></button> as control buttons like delete functionality (it also works on edit/update FYI).
Coz you can just add attribute to a button value = $id and name=delete. And it would be like an <input type='submit'> just by adding an attribute of type='submit'
So
VIEW
<table border="1" width="100%">
<tr>
<th>Name</th>
<th>Address</th>
<th>Phone Number</th>
<th>Status</th>
<th></th>
</tr>
<?php foreach($results as $row) { ?>
<tr>
<td><?=$row->name?></td>
<td><?=$row->addr?></td>
<td><?=$row->pnum?></td>
<td><?=$row->status?></td>
<?php echo form_open('delete_controller/delete_data') ?>
<td style="text-align: center">
<?php
echo "<button type='submit' name='delete' value='" . $row->id . "'>" ;
echo "DELETE" ;
echo "</button>" ;
?>
</form>
</td>
</tr>
<?php } ?>
</table>
Then it would be very simple to fetch the id of the row you want to delete. Just do this in your controller $id = $_POST['delete']; or $id = $this->input->post('delete');

Related

Codeigniter anchor tag hyperlinked to a form in controller but the data shown outside the table

I am using Codeigniter 3 and trying CRUD operation. I have created the basic crud operation and am showing the data in a table however I have linked a paragraph tag in the controller below the table to the form controller, If I want to enter another data
The issue is when I click on the link to enter another data it redirect me the original form in controller but when I enter the data and submit it, The data is shown below the table in the paragraph tag.
I am not able understand why this is happening as the controller is the same
I had faced a similar issue before when redirecting in controller.I had redirected the page after submission to show_form() controller which was basically redirecting the page to $this->load->view('learn/view_form');
in which I have kept a condition that if No data is present click to enter. Now when it redirects to show_form() controller it goes into else condition even if the data is present
CONTROLLER
<?php
defined('BASEPATH') OR exit("No direct script access allowed");
class Learning extends CI_Controller{
public function __construct(){
parent::__construct();
$this ->load->helper("url");
$this->load->model("tatti_test");
$this->load->database();
$this->load->helper();
}
//functions should be passed here
//creating a function
function start_learn() {
//this varible
$this->load->view('learn/start_learn');
}
function start_crud(){
$this->load->view('learn/form');
}
function show_form(){
$this->load->view("learn/view_form");
}
function insert_form(){
$name = $this->input->post("u_name");
$email = $this->input->post("u_email");
$mobile = $this->input->post("u_mobile");
//File Uploading
$config['upload_path']="./assets/images/";
$config["allowed_types"]="gif|jpg|png";
$config['encrypt_name']=true;
$this->load->library("upload",$config);
if(!$this->upload->do_upload("u_file")){
$file='noimage.png';
}
else {
$filework = $this->upload->data();
$file =$filework['file_name'];
}
$data = array(
"name"=>$name,"email"=>$email,"mobile"=>$mobile,"file_name"=>$file
);
$this->tatti_test->insert_tatti($data);
redirect("learning/view_form");
}
function view_form(){
$data['returned_data']=$this->tatti_test->show_form();
$this->load->view("learn/view_form",$data);
}
function delete_entry(){
$id=$this->uri->segment(3);
$data=$this->tatti_test->for_unlink($id);
$filepath="./assets/images/".$data['file_name'];
unlink($filepath);
$this->tatti_test->delete_entry($id);
redirect('learning/view_form');
}
function time_to_update(){
$id=$this->uri->segment(3);
$data['fetched_update_entry']=$this->tatti_test->update_entry($id);
$this->load->view("learn/update.php",$data); //bus associative array hi leta hai
}
function up_db(){
$name =$this->input->post('up_name');
$email = $this->input->post('up_email');
$mobile = $this->input->post('up_mobile');
$file = $this->input->post('up_file');
$id = $this->input->post('up_id');
//File Uploading
$config['upload_path']="./assets/images/";
$config["allowed_types"]="gif|jpg|png";
$config['encrypt_name']=true;
$this->load->library("upload",$config);
if(!$this->upload->do_upload("up_file")){
$data= $this->tatti_test->remove_prev($id);
$file=$data['file_name'];
}
else {
$data= $this->tatti_test->remove_prev($id);
$path="./assets/images/".$data['file_name'];
unlink($path);
$filework = $this->upload->data();
$file =$filework['file_name'];
}
$data = array(
"name"=>$name,"email"=>$email,"mobile"=>$mobile,"file_name"=>$file
);
$this->tatti_test->up_nw($data,$id);
redirect('learning/view_form');
}
} /*this accesses command from main ci controller */
?>
VIEW
<?php $this->load->view("common/header.php");
if ($returned_data != 0){ ?>
<table border='1'>
<tr>
<th>Sr No</th>
<th>Name</th>
<th>Password</th>
<th>Mobile</th>
<th>Email</th>
<th>Final Name</th>
<th>Delete</th>
<th>View</th>
</tr>
<?php $i=0; foreach ($returned_data as $key=>$d){
?>
<tr>
<td>
<?php echo ++$i; ?>
</td>
<td>
<?php echo $d['name'];?>
</td>
<td>
<?php echo $d['mobile'];?>
</td>
<td>
<?php echo $d['email'];?>
</td>
<td>
<?php echo $d['file_name'];?>
</td>
<td>
<img src="<?php echo base_url().'/assets/images/'.$d['file_name'];?>" width="100px" ; height="100px" />
</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</table>
<p>Add another entry
<?php echo anchor("learning/start_crud"," here "); ?>
</p>
<?php } ?>
<?php } else { ?>
<p>No data to show please click
<?php echo anchor("learning/start_crud"," here "); ?>to enter</p>
<?php } ?>
<?php $this->load->view("common/footer.php");
MODEL
<?php
class Tatti_test extends CI_Model{
function insert_tatti($insert_data){
$this->db->insert("f_form",$insert_data);
}
function show_form(){
$query = $this->db->get("f_form");
$response=[];
if ($query->num_rows() > 0){
$response = $query->result_array();
}
else {
$response = 0;
}
return $response;
}
function for_unlink($id){
$this->db->where("id",$id);
$query = $this->db->get("f_form");
$response=[];
foreach ($query->result_array() as $rows){
return $response = $rows;
}
}
function delete_entry($id){
$this->db->where("id",$id);
$this->db->delete("f_form");
}
function update_entry($id){
$this->db->where("id",$id);
$query = $this->db->get("f_form");
$response = [];
if($query->num_rows() > 0 ){
foreach($query->result_array() as $rows);
$response = $rows;
}
return $response;
}
function up_nw($introduced_data,$id){
$this->db->set($introduced_data);
$this->db->where('id',$id);
$this->db->update('f_form');
}
function remove_prev($id){
$this->db->where('id',$id);
$query = $this->db->get('f_form');
$response = [];
foreach($query->result_array() as $rows){
$response=$rows;
}
return $response;
}
}
?>
This is how the data is showing when clicked on the link below table
enter image description here
You're html formatting is messed up. You should have the closing </table> outside your foreach loop or premature <table> closure.
Also moved the Add another entry link outside the foreach loop. So it only appears once, and your document format not messed up.
You can use this fixed view instead:
<?php $this->load->view("common/header.php");
if ($returned_data != 0){ ?>
<table border='1'>
<tr>
<th>Sr No</th>
<th>Name</th>
<th>Password</th>
<th>Mobile</th>
<th>Email</th>
<th>Final Name</th>
<th>Delete</th>
<th>View</th>
</tr>
<?php $i=0; foreach ($returned_data as $key=>$d){
?>
<tr>
<td>
<?php echo ++$i; ?>
</td>
<td>
<?php echo $d['name'];?>
</td>
<td>
<?php echo $d['mobile'];?>
</td>
<td>
<?php echo $d['email'];?>
</td>
<td>
<?php echo $d['file_name'];?>
</td>
<td>
<img src="<?php echo base_url().'/assets/images/'.$d['file_name'];?>" width="100px" ; height="100px" />
</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<p>Add another entry
<?php echo anchor("learning/start_crud"," here "); ?>
</p>
<?php } else { ?>
<p>No data to show please click
<?php echo anchor("learning/start_crud"," here "); ?>to enter</p>
<?php } ?>
<?php $this->load->view("common/footer.php");
I realize that you are trying to do CURD,
first of all, try this to improve your code and fill the missing library of codeigniter: https://github.com/avenirer/CodeIgniter-MY_Model
For your code:
No data passed to the view in show_form(),
You should check the form submission and the conditions to load the view,
simple thing to do is follow the best practice using ready scripts,
Hope this will be useful,

Pass value while submitting a form button from model to controller

I am making an application in codeigniter. I am trying to pass value stored in a variable when a submit button is being clicked from model to controller.
How can I achieve this? I have tried the below code so far:
model.php
public function loadadd($mekhala_Id) {
echo form_open('Payment/amount($count)');
$query = $this->db->get_where('tb_unit', array('mandalam_Id' => $mekhala_Id));
echo $count= $query->num_rows();
?>
<h1>Members List</h1>
<table border="1">
<tr>
<th>Unit</th>
<th>Unit Secretary</th>
<th>Amount paid</th>
</tr>
<?php
foreach ($query->result() as $row)
{
//$i=1;
?>
<tr>
<td> <?php echo $row->unitName ;?></td>
<td> <?php echo $row->unit_sec ;?></td>
<td> <?php echo form_input(array('name'=>'na','placeholder'=>'Rupees Paid')) ;?></td>
<td><?php echo form_checkbox(array('name'=>'check','value'=>'paid')) ; ?></td>
</tr>
<?php
// $i++;
}
// echo $query->result();
echo form_submit(array('name'=>'sub','value'=>'submit'));
echo form_close();
}
public function loadpayment($paid,$count){
for($i=1;$i<=$count;$i++)
{
$a='na'.$i;
$paid=array($this->input->post($a));
$this->db->insert('tb_unit',array('Amount'=> $paid));
}
}
}
?>
controller.php public function amount($count) {
$paid=$this->input->post('na');
$this->cms_model->loadpayment($paid,$count);
}
While running this code below is being shown:
An error was encountered
The URI you submitted has disallowed characters.
I think you should read again the main idea of the model, view and controller.
The idea of the models is only to work with the database. You do not use form_open() or other html in models, this should be done in the views.
This tutorial shows more details.
To pass value with submit you can use hidden field in the form as show here.
To pass data in a variable when submit button is being clicked: you can set the variable to the value attribute: echo form_submit(array('name'=>'sub','value'=>"$variable"));

Codeigniter: How to avoid displaying duplicated values or overwrite a duplicated value in PHP foreach loop in a table?

I'm currently working on codeigniter. I want to display a value that is not been duplicated or overwrite a duplicated value from MySQL database into the datatable of PHP foreach loop.
Here is the picture my 2 tables in database:
Table "employees" & table "times"
Here is the relationship of my 2 tables:
Relation of table "employees" & table "times"
Here is my controller (home.php):
public function goPresent() { // attendance present page
$this->load->model('Model_attendance');
$query = $this->Model_attendance->getEmployees();
$data['EMPLOYEES'] = null;
if ($query) {
$data['EMPLOYEES'] = $query;
}
$this->load->view('imports/header');
$this->load->view('imports/menu');
$this->load->view('attend', $data);
}
Here is my model (model_attendance.php):
class Model_attendance extends CI_Model {
public $userID;
public $username;
public $password;
public $totime;
public $absence_type;
public $date;
public $hours;
public function getEmployees() {
$this->db->select("*");
$this->db->from('times');
$this->db->join('employees', 'employees.empnum = times.userID');
$query = $this->db->get();
return $query->result();
}
}
Here is my view (attend.php):
<table class="table table-striped responsive-utilities jambo_table" id="myTable">
<thead>
<tr class="headings">
<th>Employee No.</th>
<th>Username</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
foreach($EMPLOYEES as $employee){?>
<tr>
<td><?php echo $employee->empnum; ?></td>
<td><?php echo $employee->username; ?></td>
<td><?php echo $employee->name; ?> <?php echo $employee->lastname; ?></td>
<td><?php
if ($employee->hasClockOut==1){
echo '<a class="label label-danger">Inactive</a>';
}else {
echo '<a class="label label-success">Active</a>';
}
?></td>
</tr>
<?php } ?>
</tbody>
</table>
on which basis you want unique values, just add this line in your query....
$this->db->group_by("column name which needs to be unique");
<?php
$customers = $this->db->group_by('customer_id')->get_where('registered_table' , array(
'chat_group_id' => $group_id , 'year' => $reg_year
))->result_array();
foreach($customers as $row):?>.....
the example code above will find duplicated customer_id and avoids printing out duplicated values as you intended. Here i used group_by('customer-id')

Codeigniter shopping cart, view the contents in the cart page

Adding products to my cart is working fine, but after adding product to cart its not able to view it in my view page without refreshing view page,
I tried redirect() method still no use.
How do i view my page after adding products to cart.
Any help??
my controller:
<?php
class Cart extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function addtocart($cal_id, $f_id) {
if (empty($cal_id)) {
$this->load->view('Cart_view');
}
$this->load->model('cart_model');
$product = $this->cart_model->cart_contents($cal_id, $f_id);
foreach ($product as $row) {
$name = $row->title;
$fees = $row->fees;
}
$product = array(
'id' => $cal_id,
'qty' => 1,
'price' => $fees,
'name' => $name,
);
print_r($product);
$this->cart->insert($product);
$this->load->view('Cart_view');
}
public function destroy() {
$this->cart->destroy();
}
}
?>
my model:
<?php
class cart_model extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function cart_contents($cal_id,$f_id)
{
$product=$this->db->select('*')
->from('calander')
->join('fees','calander.cal_id=fees.cal_id')
->where('fees.cal_id',$cal_id)
->where('fees.f_id',$f_id)
->get();
return $product->result();
}
}
?>
my view
<html>
<head><title></title></head>
<body>
<?php
if ($cart = $this->cart->contents()) {
?><table>
<tr>
<td>
<h3><u>Cart page</u></h3>
</td>
</tr>
<tr>
<th>course</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<?php
foreach ($cart as $contents) {
?><tr>
<td><?php echo $contents['name']; ?></td>
<td><input type="text" value="<?php echo $contents['qty']; ?>"></td>
<td><?php echo $contents['price']; ?></td>
</tr>
<?php } ?>
</table> <?php
// redirect(base_url('/index.php/Cart/Cart_view'));
}
?>
</body>
</html>
I dont understand what you are trying to do. When you load your view $this->load->view('Cart_view');, it is required to pass the data array, containing all the variables into the view like this $this->load->view('Cart_view',$data); . Without data array, view cannot display data. When ever you write code atleast, make variables names in such a way that other people will be able to understand what that variable stands for. Without enough data, i am taking the liberty of modifying your code
Controller
public function addtocart($cal_id, $f_id) {
$data=array(
'view'=>''
);
if (empty($cal_id)) {
$this->load->view('Cart_view',$data);
} else {
$this->load->model('cart_model');
$product = $this->cart_model->cart_contents($cal_id, $f_id);
$data['view']='';
foreach($product as $row):
$data['view'].=' <tr>
<td>'.$row->title.'</td>
<td>'.$row->qty.'</td>
<td>'.$row->price.'</td>
</tr>';
endforeach;
$this->load->view('Cart_view',$data);
}
}
MODEL
public function cart_contents($cal_id,$f_id){
$this->db->select('*')
$this->db->from('calander')
$this->db->join('fees','calander.cal_id=fees.cal_id')
$this->db->where('fees.cal_id',$cal_id)
$this->db->where('fees.f_id',$f_id);
$query = $this->db->get();
return $query->result();
}
view
<html>
<head><title></title></head>
<body>
<table>
<tr>
<td>
<h3><u>Cart page</u></h3>
</td>
</tr>
<tr>
<th>course</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<?php if($count>0){
echo $view;
}?>
</table>
</body>
</html>

how to display content from database in codeigniter without calling controller from view?

I am new to codeigniter. I followed a video tutorial and successfully created a login registration system. After registration or login the users reach a page called members.php.
members.php is a view.
my controller is main.php and model is model-users.php.
I want members.php to show/have content from the database so that the users can read it once the login or register?
I followed a few resources on the web that said not to call controller from view. How can I accomplice the above without doing so?
Thanks
I think the CodeIgniter documentation is actually very clear, and very easy to follow. Nevertheless, here's an example of how you might structure your app.
Controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Members extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('members_model');
}
function index() {
$data['members'] = $this->members_model->get_members();
$this->load->view('header', $data);
$this->load->view('members');
$this->load->view('footer');
}
}
Model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Members_model extends CI_Model {
function get_members() {
$query = $this->db->get('members');
return $query->result_array();
}
}
View:
<?php
print_r($members);
To access the above page, you would visit http://yoursite.com/index.php/members.
You can use a .htaccess file to remove the index.php segment from the URI. The index() method is automatically called when you run a controller.
I don't have any example of the code, but I write one simple example of HTML when you can show name and surname of members.
Controller:
function members(){
$members = $this->model-user->get_list(); //array of members
$this->load->view('members.php', $members); // load members in view
}
View members.php
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
<?php foreach($members as $m): ?>
<tr>
<tr><?php echo $m['name']; ?>
<tr><?php echo $m['surname']; ?>
</tr>
<?php endforeach; ?>
<table>
</body>
</html>
Model:
function get_list() {
// query in database
return $query = $this->db->get('members'); //table name members
}
This is the simple example in a short form. I hope that you will understand it.
I think i know what you mean, this is definitely not the right way to go about this but if you really must you could call a model from a view like this.
In the view
<div>
<?php
#You could load the model here or autoload it in config->autoload->models(i believe)
$data = $this->model_name->model_function();?>
foreach($data as $row):
echo '<pre>';
print_r($row);
echo '</pre>';
endforeach;
?>
</div>
here is the example of my codes:
views:
<?php foreach($ecms as $i){ ?>
<tr>
<td><?php echo $i->accnum; ?></td>
<td><?php echo $i->crdnum; ?></td>
<td><?php echo $i->fname; ?></td>
<td><?php echo $i->bday; ?></td>
</tr>
<?php } ?>
model:
function masterHide()
{
$sql =" select * from ecms";
$query = $this->db->query($sql);
return($query->num_rows() > 0) ? $query->result(): NULL;
}
controller:
function search() {
// $this->MasterListAccess();
$this->load->model('navi_model');
$query = $this->navi_model->masterHide();
//check results or returned value of model
//print_r($query);
$data['ecms'] = $query;
$data['main_content'] = 'search';
$this->load->view('includes/template',$data);
}
At first connect the database in your project file and connect the model page in your view page and try this code.
Go to the view page and try this code
View
20
21
<?php
$get_data=$this->MyModel->get_table_data();
?>
<table class="table table-bordered">
<thead>
<tr>
<th> Name </th>
<th> Email </th>
<th> Phone No </th>
</tr>
</thead>
<tbody>
<?php foreach($get_data as $val){ ?>
<tr>
<td><?php echo $val->name; ?></td>
<td><?php echo $val->email; ?></td>
<td><?php echo $val->phone; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Model
public function get_table_data(){ $qry=$this->db->select('*')->from('Table Name')->get()->result(); return $qry; }

Categories