Using CodeIgniter I am trying to create a link that the user can click within a view to show them the details of a record in my database.
In ASP.NET MVC3 with C# I would do it with #Html.ActionLink("Controller", "Action", new { id = item.Id})
This is my session controllers index() function
public function index()
{
$data['sessions'] = $this->session_model->get_sessions();
$this->load->view('_header');
$this->load->view('session/index', $data);
$this->load->view('_footer');
}
This is the index view it loads where I want to be able to click the link to go to enter() function
<table>
<th>Session Name</th>
<th>Description</th>
<th>Host</th>
<th></th>
<?php foreach ($sessions as $session_item): ?>
<tr>
<td> <?php echo $session_item['sessionName'] ?> </td>
<td> <?php echo $session_item['sessionDesc'] ?> </td>
<td> <?php echo $session_item['adminName'] ?> </td>
<td> <a id="enterSession" href=<?php echo site_url("session/enter" + $session_item['id']) ?> >Enter</a></td>
</tr>
<?php endforeach ?>
The enter session points me to the url "http://192.168.1.36/index.php/1" (if the id of my item is 1) whereas I expect "http://192.168.1.36/index.php/session/enter/1"
Any ideas on how I can make it call the enter() function also in the session controller (shown below)
public function enter($id) {
$this->load->view('_header');
$this->load->view('session/enter');
$this->load->view('_footer');
}
There seems to be a typo in the string concatenation in your PHP code. Perhaps it will work to use:
site_url("session/enter" . $session_item['id'])
... rather than a + sign between the two strings.
Regarding the second question - it looks correct as-is. Is it failing to call the session controller's enter() function passing the $id as an argument (assuming the URL is correct)?.
Related
I'm trying to practice OOP but with native PHP.
I have my 'controller', My_Controller.php:
session_start();
if (!isset($_SESSION['userId'])) exit('You are not authorized to access this page');
// ... some code ...
if(isset($_GET['action']))
{
switch($_GET['action']) {
case 'getOrder':
if(isset($_GET['id'])) {
$orderDetails = $jobModel->getOrderById($_GET['id']);
header('Location: order-details.php');
}
break;
default:
echo 'Invalid action';
break;
}
}
And this is my 'view', order-details.php:
<?php
require_once './My_Controller.php';
?>
<html>
<head>
<title>Order Details</title>
</head>
<body>
<div>
Back to Order List
</div>
<div>Order Details</div>
<div>
<form id="form-add-job-item" method="post" action="">
<table border="1">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
if(isset($orderDetails) && $orderDetails != 0) {
foreach($orderDetails as $orderItem => $value) {
?>
<tr>
<td><?= $value->name; ?></td>
<td><?= $value->quantity; ?></td>
<td><?= $value->amount; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<button type="submit">Add Item</button>
</form>
<?php
?>
</div>
</body>
</html>
order-details.php is some sort of a template to display the information for every order depending on the contents of $orderDetails.
It is called via separate page containing a table of orders. Each order in the table has a link:
<tr>
<td><?= $value->job_id; ?></td>
<td><?= $value->job_date; ?></td>
<td><?= $value->total_amount; ?></td>
</tr>
This is so it can be dynamic, in that I won't have to code a separate page for each order. This template will just hold variables and those variables will be filled with the relevant information based on the passed order ID, which will depend on what link the user clicked.
WHAT I NEED TO ACCOMPLISH:
I need to access the contents of $orderDetails and show the list of order items in order-details.php but I'm not sure how to do that? With what I have so far, I get a NULL value from the $orderDetails variable when accessing it from order-details.php.
I have checked the results from the database query using var_dump($orderDetails) and it does return the expected results.
UPDATE:
inside My_Controller.php:
case 'getOrder':
if(isset($_GET['id'])) {
// $dba contains the connection to the database
$MyController = new My_Controller($dba);
$MyController->getOrderById($_GET['id']);
}
break;
// ... Some code ...
class My_Controller
{
private $myModel;
public function __construct(Db $db)
{
$this->myModel = new My_Model($db);
}
public function getOrderById($orderId)
{
$orderDetails = $this->myModel->getOrderById($orderId);
include './order-details.php';
}
}
That variable will be accessible without doing anything special because it is in global scope. In other words, you can just access it as $orderDetails.
The trick is that it has to be defined. The way your code in My_Controller.php is set up, $_GET['action'] must be equal to getOrder and $_GET['id'] must be defined, or $orderDetails will not be set.
Here's the catch: this line of code ensures that $orderDetails is never set when you get to your display logic:
header('Location: order-details.php');
This redirect doesn't preserve the $_GET parameters. It triggers a brand new request with no parameters. So, after the redirect, your logic loading the order details never runs.
As for how to solve it: that depends on what you're trying to do, but most likely you shouldn't have that redirect there at all.
Also, you should know that using lots of global variables like this is considered bad practice. You should start breaking your code into small, reusable chunks using functions or objects.
I am making a table from a database and want to add an Edit/delete button to each row update or delete a specific row from the database. I have successfully added working "delete" button but I have no idea how could I update data in table <td> in view and send it to controller.
Here is my code:
view file
<table class="table table-striped">
<tr>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>class</td>
<td>roll no.</td>
</tr>
<?php foreach($record as $r): ?>
<tr>
<td><?php echo $r->name; ?></td>
<td><?php echo $r->age; ?></td>
<td><?php echo $r->gender; ?></td>
<td><?php echo $r->class; ?></td>
<td><?php echo $r->roll no; ?></td>
<td><a href="" >Edit</a>
<a href="<?php echo base_url()."student/deleteRow" ?id="$r->name">"
onclick="return confirm
('Are you sure to Delete?')"><i class="icon-trash"></a></td>
</tr>
<?php endforeach; ?>
</table>
Controller Function
public function deleteRow(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->student_model->rowDelete($id);
redirect($_SERVER['HTTP_REFERER']);
}
}
I don't know how can I now insert an input field to update table row without effecting previous view. Any suggestion would be helpful.
To Edit the Studen data you need to pass an id or uniue column name to the data base to get that student data.
First Set the student id in <a href=""> tag.
<td><a href="<?= base_url('student/edit_student') ?>/$r->id" >Edit</a>
Then When you click on the edit it will take you to the controller. You can get the third url parameter direct in as show in the controler code:
You can also use get as shon
Your Controller should be:
public function edit_student($id){
$student_data = $this->student_model->get_student_data($id);
$this->load->view('your_view',['student_data'=>$student_data)]);
}
Here is you model which get the id form controllr and find the student data and passit to back to the controller:
Your Model should be:
public function get_student_data($id){
$this->db->select('*');
$this->db->from('your_table_name');
$this->db->where('id',$id);
$query = $this->db->get();
$student_data = $query->$row_array();
if(isset($student_data) && !empty($student_data)){
return student_data;
} else {
return FALSE;
}
}
Form controller you pass the data to the view.
On View Side:
<?php
// Just to ensure the data. Comment it after testing
echo "<pre>";
print_r($student_data);
echo "</pre>";
?>
<form action="<?= base_url('student/update_student') ?>/<?= $student_data['id'] ?>">
<input name="your_column_name" value="<?= $student_data['your_column_name'] ?>">
// Try to do the same for all you column.
<input type="submit" value="updata">
</form>
Here is the controller for update the data
public function update_student($id){
$student_data = $this->input->post();
$status = $this->student_model->update_student($id,$student_data);
if($status == TRUE){
$this->load->view('your_view');
// Your Success view
} else {
// Your view if fail to update
$this->load->view('your_view');
}
}
Here is the model for update the data
public function get_student_data($id,$student_data){
$this->db->where('id',$id);
$this->db->update('your_table_name',$student_data);
if($this->db->affected_rows() == 1){
return TRUE;
} else {
return FALSE;
}
}
Very similar to what you have done for delete. Something like this:
<td>
<a href="" >Edit/Delete</a>
<!-- This should be another method in Student controller -->
<i class="icon-trash"><!-- I changed order of edit and delete -->
</td>
I need to warn you for CSRF. If you don't implement better security here, anyone pointing to that link would be able to edit or delete data.
Check Security class in documentation and how to set hidden value so that way you would ensure that only one who has already requested that page was able to edit/delete rows.
<td><a href="<?php echo base_url();?>controller_name/function_name/<?php echo $edit_id;?>" >Edit</a></td>
another way
<td><a href="<?php echo base_url();?>controller_name/function_name?id=<?php echo $edit_id;?>" >Edit</a></td>
You can use any one according to your requirement.
I am new to PHP and codeigniter and I've been encountering a lot of PHP errors, such as Invalid argument supplied for foreach() and Undefined variable: row and query. In my views i tried to foreach it as (query->results() as $row) and the errors lesson to 1 which is an undefined varaiable: query
I'm not really sure which part I am missing, I already have declared query in my model, It seems that the controller was not able to receive the passed variable. Can anyone correct my mistake? and would give an explanation to avoid such mistakes in the future. Thanks!
Model function:
function getStudentInfo()
{
$this->db->select("firstname,middlename,lastname");
$this->db->from('studentinfo');
$query = $this->db->get();
return $query->result();
}
Controller function:
public function index()
{
$this->data['query'] = $this->m_login->getStudentInfo(); //i passed the query to the data variable
$this->load->view('v_home', $this->data);
}
Views:
<!DOCTYPE html>
<head>
<title>Simple Login with CodeIgniter - Private Area</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $studentid; ?>!</h2>
Logout
<h4>Display Records From Database Using Codeigniter</h4>
<table>
<tr>
<td><strong>First Name</strong></td>
<td><strong>Last Name</strong></td>
</tr>
<?php foreach($query as $row){?>
<tr>
<td><?php echo $row->firstname;?></td>
<td><?php echo $row->lastname;?></td>
</tr>
<?php }?>
</table>
</body>
</html>
Your procedure seems ok.
You made following error.
<?php foreach($query as $row);?>//your foreach ends here for this comma
//those lines are out of foreach
<?php echo $row->firstname;?>//$row is undefined and $row->firstname is invalid property
<?php echo $row->lastname;?>//same for lastname
<?php ?>
use this way.
<?php foreach($query as $row){?>
<?php echo $row->firstname;?>
<?php echo $row->lastname;?>
<?php } ?>
I have form where the select boxes are there and select all option, i want to post all the data without click on check boxes, i dont want to view this page, mean if user go to signup page the data will already selected by default how can i do that wothout any view?
this is my view code
<?php v_start($this);?>
<?php
#if(element exits of controller-action)
echo $this->element('validations/users/signup');
?>
<script>
function toggleChecked(status)
{
jQuery(".new-checkbox input").each( function() {
jQuery(this).attr("checked",status);
}
)
}
</script>
<h1><span style="color:CornflowerBlue"><?php echo __l('Step1');?></span></h1>
<?php
$form = $this->FormManager;
echo $form->create('User',array_merge($form_options,array('default'=>true)));
?>
<table width = "100%">
<tbody>
<tr>
<td>
<?php echo $form->input('',array('id'=>'mark-all','onclick'=>'toggleChecked(this.checked)','type'=>'checkbox','label'=>'Select All Products' ));?>
<?php echo $form->input('product_id',
array(
'multiple'=>'checkbox',
'options'=>$products,
'div'=>false,
'class'=>'new-checkbox'
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
echo $this->FormManager->end(LBL_BTN_NEXT);
?>
</td>
</tr>
</tbody>
</table>
i dont want this page, the user will select the data by default.
this is my controller code
$products = $this
->User
->ProductsUser
->Product
->find('list',array(
'fields' => 'product_id,name',
'conditions'=>array(
'Product.is_visible'=>true
)
)
);
$this->set('products',$products);
if($this->request->is('post'))
{
$this->Session->write('signUp.signUpProduct',$this->request->data['User']);
$this->redirect(array('action'=>'signup_product'));
}
}
how can i do that, Thanks in advance.
The attr() doesn't take true or false as an argument.
jQuery(this).attr("checked","checked"); // Correct usage of attr()
Although I think attr is deprecated for the favorable prop() method.
jQuery(this).prop("checked",status);
Which indeed does take a true/fales argument. :)
Hope this helps.
i am trying to implement jquery datatable, in my cakePHP based website, but it just wont load. this website is already half developed, and from the way i see it, the js' is loaded through a file called _head.inc.ctp located inside the views/layouts folder, i have added the datatables library inside the libs folder which is webroot/js/libs and load it inside the _head.inc.ctp file.
suppose i have this:
my controller:
var $helpers = array(
'Form',
'Html',
'Javascript'
);
//my method
function dataTable_example($id=null){
$details = $this->Detail->find("all");
$this->set('details', $details );
}
my view:
<div>
<?php echo $javascript->link('libs/jquery.dataTables.js'); ?>
<script>
$(document).ready(function(){
$('#js-datatable').dataTable();
});
</script>
<h2><?php echo __l('Tickets');?></h2>
<div>
<table id="js-datatable">
<tr>
<th>some heading 1</th>
<th>some heading 1</th>
<th>some heading 1</th>
</tr>
<?php
if (!empty($details)){
foreach ($details as $detail):
?>
<tr>
<td><?php echo $detail['Detail']['id'];?></td>
<td><?php echo $detail['Detail']['created'];?></td>
<td><?php echo $detail['Detail']['ticket_detail'];?></td>
</tr>
<?php
endforeach;
}else{
?>
<tr>
<td>No Data Found</td>
</tr>
<?php }?>
</table>
</div>
</div>
i even hard coded it using the usual call, and checked it using firebug to see if the script is loaded or not, and according to firebug, it is loaded, so i cant see whats making the script fail my table.
did i missed some steps ? please help
thanks
You don't have thead and tbody elements as required by the datatables script
You should use the find function in your controller and pass the array to the view and in the view write it.. don't just leave the table empty