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>
<a href="order-list.php">Back to Order List</a>
</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><a href="My_Controller.php?action=getOrder&id=<?= $value->job_id; ?>"><?= $value->job_id; ?></a></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';
}
}