Accessing values from a different php file? - php

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.

Related

update table row and save in database in php codeigniter

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.

Getting an info from the DB with Tables and Updating it

Hi guys im having a difficulty with this scenario:
I want to get the product information using modals, i got this following code:
//Model.php
public function getProduct($product_id){
$this->db->select('product_id,product_name,product_price,product_qty');
$this->db->from('tbl_products');
$this->db->where('product_id',$product_id);
$query = $this->db->get();
return $query->result();
}
//Controller.php
public function view_product(){
$product_id = $this->input->post('product_id');
$this->load->view('header');
$this->data["post"] = $this->Model->ProductList();
$this->load->view('product_page',$this->data);
$this->data["post"] = $this->Model->getProduct($product_id);
$this->load->view('modal/update_product',$this->data);
}
//update_product.php (modal) my View
lets just go straight into the form
<form action="" method="post">
<?php foreach($posts as $post){ ?>
<input type = "hidden" name = "product_id" value = "<?php echo $post->product_id;?>"/>
<input type = "text" name = "product_name" value = "<?php echo $post->product_name;?>"/>
<input type = "text" name = "product_price" value = "<?php echo $post->product_price;?>"/>
<input type = "text" name = "product_qty" value = "<?php echo $post->product_qty;?>"/>
<button type="submit">Update</button>
<?php } ?>
</form>
I got a table already: i can see all products, in my product_page.php
Here is the tables face looks like:
ID Name Price Quantity Option
1 Shoes 150.00 1 Update
2 Liquor 67.50 5 Update
3 Paint 1000.00 5 Update
Once I click the Update button, the update_product.php(a modal) will pop up and get the result of 1 of the product, if I press the first Update only the information for Shoes will be inside the modal, at first i tried it, I get all the information of all the products which makes my modal redundant and looping due to foreach, then I tried getting the information from the table ID itself, and no product pops out, how can I see only 1 product using modal? thank you very much maam and sirs. Please I really need youre help :(
Although I'm not really clear what you're asking, Here is an answer to you question. Your controller code doesn't seem to be making any sense.If you want to display all your products in on page and then you want to edit/update a product when clicked on corresponding update link, here is what you can do.
Use single controller method for list and update
//Controller.php
public function view_product(){
$product_id = (isset($this->input->post('product_id')) ? $this->input->post('product_id'): False ;
if($product_id == False){
$this->data["post"] = $this->Model->ProductList();
$this->load->view('product_page',$this->data);
} else{
$this->data["post"] = $this->Model->getProduct($product_id);
$this->load->view('modal/update_product',$this->data);
}
}
This is simple modification to your code to make it work correctly, but since this code cannot handle form submission of the update form (unless you're pointing update form to a different controller), you will have to add some other code to this controller and your code will get messy in no time. My personal suggestion to you is this,
Use different controllers for list view and update
//Controller.php
public function view_product(){
$this->data["post"] = $this->Model->ProductList();
$this->load->view('product_page',$this->data);
}
public function update_product($product_id){
if($this->input>post('submit')){ // 'submit'should be replaced with the name attribute of your submit button
//call your model and handle the update form submission here
}
$this->data["post"] = $this->Model->getProduct($product_id);
$this->load->view('product_page',$this->data);
}
now, update option of your product_page.php should point to 'update_product' controller method with corresponding product id e.g. {base_url}/controller_class_name/update_product/1
I think your product_page.php has some code like this to loop through all the products and display products in a table, now when you click update link it will point to update_product controller and it will handle the update process.
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<?php if(!$products){ ?>
<tr>
<td colspan="5">No result</td>
</tr>
<?php } ?>
<?php if($products){ ?>
<?php foreach ($products as $product) { ?>
<tr>
<td><?php echo $product->id; ?></td>
<td><?php echo $product->name; ?></td>
<td><?php echo $product->price; ?></td>
<td><?php echo $product->quantity; ?></td>
<td>
<a href="<?php echo base_url(); ?>controller_class_name/update_product/<?php echo $product->id; ?>" >Update</a>
</td>
</tr>
<?php } } ?>
</tbody>
</table>
You won't be needing a foreach loop inside your update_product.php because you're updating only one product at once.
Hope this is the answer you're looking for, if not please comment and I will edit the answer accordingly.

Retrieving data in codeigniter: passing variables but not identified

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 } ?>

How to Set a MYSQL Variable Value to 1 when text is clicked in php?

First off I know very little about php and am still learning so please go easy on me with your answers. Basically I'm working on a project that functions like a social network site, users are able to send and receive private messages etc. I have got this all working great and the messages even go to the messages_deleted.php page when you set the variable value from '0' to '1' in the database.
Is there a way to let the user do this themselves, to delete their own messages by clicking a piece of text?
I'm working in php so would need a piece of php code which allows me to do this if anyone has any ideas?
Here is my current php script I'm using:
<?php
$page_title = "Messages";
include('includes/header.php');
confirm_logged_in();
include ('includes/mod_login/login_form.php');
?>
<div class="modtitle">
<div class="modtitle-text">Inbox</div>
</div>
<div class="modcontent">
<strong>Inbox</strong> | Sent Messages | Deleted
<br /><br />
<table width="100%" border="0" cellpadding="5" cellspacing="0">
<tr bgcolor="#CCCCCC">
<td width="30%"><strong>Recieved</strong></td>
<td width="20%"><strong>From</strong></td>
<td width="28%"><strong>Subject</strong></td>
<td width="0%"><strong>Read/Unread</strong></td>
<td width="0%"><strong>Delete</strong></td>
</tr>
<?php
$inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set)) {
?>
<?php
if ($inbox['read'] == 0) { ?>
<tr bgcolor="#6666B3">
<?php }
if ($inbox['read'] == 1) { ?>
<tr>
<?php } ?>
<td><?php
$datesent1 = $inbox['date_sent'];
echo "$datesent1"; ?></td>
<td><?php echo "<a href=\"profile.php?id={$inbox['from_user_id']}\">{$inbox['display_name']}"; ?></td>
<td><?php echo "<strong>{$inbox['subject']}</strong>"; ?></td>
<td><?php if ($inbox['read'] == 0) {
echo "Unread";
}
if ($inbox['read'] == 1) {
echo "Read";
}
?></td>
<td>
<?php
if ($inbox['delete'] == 0) {
echo "Delete";
}
if ($inbox['delete'] == 1) {
echo "$deleted_set;";
}
; ?></td>
</td>
<?php
}
?>
</tr>
</table>
</div>
<?php include('includes/footer.php'); ?>
What I really need is a way of making the 'delete' row clickable so that when a user clicks on it it sets the value to '1'. If it can be done that way it would be a lot easier for me I think.
Yes. It is quite simple. You can take a look at some basic jQuery and AJAX working on the page. Here's a link to documentation of the API.
if you dont want to use Ajax, you should create a link that redirects user to a page for example delete_message.php?mid=16 where mid is the message id users wants to delete,
then on server side first check that this message belongs to the user that wants to delete it, so a user cant delete other peoples messages,
then run a mysql code whish should look like this : UPDATEmessagesSETdeleted= '1' WHEREid= '16'
i hope it helps you, let me know if you had any other questions.
Assumptions
If you can include jQuery to your project, then you can use PHP + AJAX to work on this. Say, you have the PHP file which makes the message deleted as messages_deleted.php. And to delete a message, I assume that, you need to pass a parameter id to the script, which finally comes this way: messages_deleted.php?id=5.
Also assuming that the code in your PHP file is:
<?php
mysql_connect();
if (mysql_query("UPDATE `messages` SET `deleted` = 1 WHERE `id` = " . mysql_real_escape_string($_GET["id"])))
die ("deleted");
else
die ("error");
?>
Code
You can use jQuery's $.getScript() to do the work for you.
And if the message is valid and deleted, your PHP Script should die("deleted");. Adjust accordingly.
$(document).ready(function(){
$("table tr").click(function(){
$.getScript("messages_deleted.php", function(data){
if (data == "deleted")
alert("Message Deleted");
});
});
});

Link to a Controller function with parameter from a View (CodeIgniter)

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)?.

Categories