Implement linked list in php - php

How should I implement a linked list in PHP? Is there a implementation built in into PHP?
I need to do a lot of insert and delete operations, and at same time I need to preserve order.
I'd like to use only PHP without any special extensions.

There is SplDoublyLinkedList. Is this okay, too?

Here is a linked list implementation in PHP pulled from: http://www.codediesel.com/php/linked-list-in-php/ which can add, delete, reverse and empty a linkedlist in PHP.
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//insertion at the start of linklist
public function insertFirst($data)
{
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
//displaying all nodes of linklist
public function readList()
{
$listData = array();
$current = $this->firstNode;
while($current != NULL)
{
array_push($listData, $current->readNode());
$current = $current->next;
}
foreach($listData as $v){
echo $v." ";
}
}
//reversing all nodes of linklist
public function reverseList()
{
if($this->firstNode != NULL)
{
if($this->firstNode->next != NULL)
{
$current = $this->firstNode;
$new = NULL;
while ($current != NULL)
{
$temp = $current->next;
$current->next = $new;
$new = $current;
$current = $temp;
}
$this->firstNode = $new;
}
}
}
//deleting a node from linklist $key is the value you want to delete
public function deleteNode($key)
{
$current = $this->firstNode;
$previous = $this->firstNode;
while($current->data != $key)
{
if($current->next == NULL)
return NULL;
else
{
$previous = $current;
$current = $current->next;
}
}
if($current == $this->firstNode)
{
if($this->count == 1)
{
$this->lastNode = $this->firstNode;
}
$this->firstNode = $this->firstNode->next;
}
else
{
if($this->lastNode == $current)
{
$this->lastNode = $previous;
}
$previous->next = $current->next;
}
$this->count--;
}
//empty linklist
public function emptyList()
{
$this->firstNode == NULL;
}
//insertion at index
public function insert($NewItem,$key){
if($key == 0){
$this->insertFirst($NewItem);
}
else{
$link = new ListNode($NewItem);
$current = $this->firstNode;
$previous = $this->firstNode;
for($i=0;$i<$key;$i++)
{
$previous = $current;
$current = $current->next;
}
$previous->next = $link;
$link->next = $current;
$this->count++;
}
}
}
$obj = new LinkList();
$obj->insertFirst($value);
$obj->insert($value,$key); // at any index
$obj->deleteNode($value);
$obj->readList();

Here is the code in php which will implement Linked List, only with the reference of head node i.e first node and then you add at first, last and delete a key, and also maintain the code of the keys in list.
<?php
/**
* Class Node
*/
class Node
{
public $data;
public $next;
public function __construct($item)
{
$this->data = $item;
$this->next = null;
}
}
/**
* Class LinkList
*/
class LinkList
{
public $head = null;
private static $count = 0;
/**
* #return int
*/
public function GetCount()
{
return self::$count;
}
/**
* #param mixed $item
*/
public function InsertAtFist($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
$temp = new Node($item);
$temp->next = $this->head;
$this->head = $temp;
}
self::$count++;
}
/**
* #param mixed $item
*/
public function InsertAtLast($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
/** #var Node $current */
$current = $this->head;
while ($current->next != null)
{
$current = $current->next;
}
$current->next = new Node($item);
}
self::$count++;
}
/**
* Delete the node which value matched with provided key
* #param $key
*/
public function Delete($key)
{
/** #var Node $current */
$current = $previous = $this->head;
while($current->data != $key) {
$previous = $current;
$current = $current->next;
}
// For the first node
if ($current == $previous) {
$this->head = $current->next;
}
$previous->next = $current->next;
self::$count--;
}
/**
* Print the link list as string like 1->3-> ...
*/
public function PrintAsList()
{
$items = [];
/** #var Node $current */
$current = $this->head;
while($current != null) {
array_push($items, $current->data);
$current = $current->next;
}
$str = '';
foreach($items as $item)
{
$str .= $item . '->';
}
echo $str;
echo PHP_EOL;
}
}
$ll = new LinkList();
$ll->InsertAtLast('KP');
$ll->InsertAtLast(45);
$ll->InsertAtFist(11);
$ll->InsertAtLast('FE');
$ll->InsertAtFist('LE');
$ll->InsertAtFist(100);
$ll->InsertAtFist(199);
$ll->InsertAtLast(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(45);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(100);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
Code out put as:
$ php LinkList.php
199->100->LE->11->KP->45->FE->500->
Total elements 8
199->100->LE->11->KP->FE->500->
Total elements 7
199->100->LE->11->KP->FE->
Total elements 6
199->LE->11->KP->FE->
Total elements 5

Here is another Linked list implementation using an array of elements. The add function keeps the elements sorted.
<?php
class LinkedList{
private $_head = null;
private $_list = array();
public function addNode($val) {
// add the first element
if(empty($this->_list)) {
$this->_head = $val;
$this->_list[$val] = null;
return;
}
$curr = $this->_head;
while ($curr != null || $curr === 0) {
// end of the list
if($this->_list[$curr] == null) {
$this->_list[$curr] = $val;
$this->_list[$val] = null;
return;
}
if($this->_list[$curr] < $val) {
$curr = $this->_list[$curr];
continue;
}
$this->_list[$val] = $this->_list[$curr];
$this->_list[$curr] = $val;
return;
}
}
public function deleteNode($val) {
if(empty($this->_list)) {
return;
}
$curr = $this->_head;
if($curr == $val) {
$this->_head = $this->_list[$curr];
unset($this->_list[$curr]);
return;
}
while($curr != null || $curr === 0) {
// end of the list
if($this->_list[$curr] == null) {
return;
}
if($this->_list[$curr] == $val) {
$this->_list[$curr] = $this->_list[$val];
unset($this->_list[$val]);
return;
}
$curr = $this->_list[$curr];
}
}
function showList(){
$curr = $this->_head;
while ($curr != null || $curr === 0) {
echo "-" . $curr;
$curr = $this->_list[$curr];
}
}
}
$list = new LinkedList();
$list->addNode(0);
$list->addNode(3);
$list->addNode(7);
$list->addNode(5);
$list->addNode(2);
$list->addNode(4);
$list->addNode(10);
$list->showList();
echo PHP_EOL;
$list->deleteNode(3);
$list->showList();
echo PHP_EOL;
$list->deleteNode(0);
$list->showList();
echo PHP_EOL;
The output is:
-0-2-3-4-5-7-10
-0-2-4-5-7-10
-2-4-5-7-10

I was also trying to write a program to create a linked list in PHP. Here is what I have written and it worked for me. I hope it helps to answer the question.
Created a php file. Name: LinkedList.php
{code}
<?php
require_once (__DIR__ . "/LinkedListNodeClass.php");
$node_1 = new Node();
Node::createNode($node_1, 5);
echo "\n Node 1 is created.";
$head = &$node_1;
echo "\n Head is intialized with Node 1.";
$node_2 = new Node();
Node::createNode($node_2, 1);
echo "\n Node 2 is created.";
Node::insertNodeInLinkedList($head, $node_2);
$node_3 = new Node();
Node::createNode($node_3, 11);
echo "\n Node 3 is created.";
Node::insertNodeInLinkedList($head, $node_3);
$node_4 = new Node();
Node::createNode($node_4, 51);
echo "\n Node 4 is created.";
Node::insertNodeInLinkedList($head, $node_4);
$node_5 = new Node();
Node::createNode($node_5, 78);
echo "\n Node 5 is created.";
Node::insertNodeInLinkedList($head, $node_5);
$node_6 = new Node();
Node::createNode($node_6, 34);
echo "\n Node 6 is created.";
Node::insertNodeInLinkedList($head, $node_6);
$node_7 = new Node();
Node::createNode($node_7, 99);
echo "\n Node 7 is created.";
Node::insertNodeInHeadOfLinkedList($head, $node_7);
$node_8 = new Node();
Node::createNode($node_8, 67);
echo "\n Node 8 is created.";
Node::insertNodeInHeadOfLinkedList($head, $node_8);
$node_9 = new Node();
Node::createNode($node_9, 101);
echo "\n Node 9 is created.";
Node::insertNodeAfterAPositionInLinkedList($head, 5, $node_9);
$node_10 = new Node();
Node::createNode($node_10, 25);
echo "\n Node 10 is created.";
Node::insertNodeAfterAPositionInLinkedList($head, 2, $node_10);
echo "\n Displaying the linked list: \n";
Node::displayLinkedList($head);
?>
{code}
This file is calling a class to create, insert and display nodes in linked list. Name: LinkedListNodeClass.php
{code}
<?php
class Node {
private $data;
private $next;
public function __construct() {
//does nothing...
}
//Creates a node
public function createNode($obj, $value) {
$obj->data = $value;
$obj->next = NULL;
}
//Inserts a created node in the end of a linked list
public function insertNodeInLinkedList($head, &$newNode) {
$node = $head;
while($node->next != NULL){
$node = $node->next;
}
$node->next = $newNode;
}
//Inserts a created node in the start of a linked list
public function insertNodeInHeadOfLinkedList(&$head, &$newNode) {
$top = $head;
$newNode->next = $top;
$head = $newNode;
}
//Inserts a created node after a position of a linked list
public function insertNodeAfterAPositionInLinkedList($head, $position, &$newNode) {
$node = $head;
$counter = 1;
while ($counter < $position){
$node = $node->next;
$counter++;
}
$newNode->next = $node->next;
$node->next = $newNode;
}
//Displays the Linked List
public function displayLinkedList($head) {
$node = $head;
print($node->data); echo "\t";
while($node->next != NULL){
$node = $node->next;
print($node->data); echo "\t";
}
}
}
?>
{code}

If don't think most people understand what linked lists are. The basic idea is you want to keep data organised is such a way that you can access the previous and next node using the current node. The other features like add, delete, insert, head etc are sugar, though necessary. I think the SPL package does cover a lot. Problem is I need a PHP 5.2.9 class. Guess I've to implement it myself.

Just to clarify, implementing linked list in PHP using PHP arrays probably is not a good idea, because PHP array is hash-table under the hood (not simple low-level arrays). Simultaneously, you don't get advantages of pointers.
Instead, you can implement data structures like linked list for PHP using extensions, that means you are implementing a data structure in C to PHP.
Spl data structures are an example, another example is php-ds extension, specially in case of linked lists, you can use this: https://www.php.net/manual/en/class.ds-sequence.php
Sequence ADT is the unification of List ADT and Vector ADT, so you can use Sequence ADT implemented data structures as lists.
Hope this could help someone choose wisely.

// Here's a basic implementation of SplDoublyLinkedList using PHP.
$splDoubleLinkedList = new SplDoublyLinkedList();
$splDoubleLinkedList->push('a');
$splDoubleLinkedList->push('3');
$splDoubleLinkedList->push('v');
$splDoubleLinkedList->push('1');
$splDoubleLinkedList->push('p');
// $splDoubleLinkedList->unshift('10');
// $splDoubleLinkedList->pop();
$splDoubleLinkedList->add(3, 3.0);
// First of all, we need to rewind list.
$splDoubleLinkedList->rewind();
// Use while, check if the list has valid node.
while($splDoubleLinkedList->valid()){
// Print current node's value.
echo $splDoubleLinkedList->current()."\n";
// Turn the cursor to next node.
$splDoubleLinkedList->next();
}

Related

Error when printing how many levels are visible in tree in PHP

I am receiving the error "Using $this when not in object context". I think I might be using the class node incorrectly. I cannot figure out where I am going wrong at this point.
I am trying to get the answer 4 in the case of a tree like the below. This is because there are 4 visible layers.
$root = new TreeNode(8);
$root->left = new TreeNode(3);
$root->right = new TreeNode(10);
$root->left->left = new TreeNode(1);
$root->left->right = new TreeNode(6);
$root->left->right->left = new TreeNode(4);
$root->left->right->right = new TreeNode(7);
$root->right->right = new TreeNode(14);
$root->right->right->left = new TreeNode(13);
class TreeNode{
public $val;
public $left;
public $right;
public function __construct($val=0) {
$this->val = $val;
$this->left = NULL;
$this->right = NULL;
}
}
function findLeft($root){
$queue = $root;
while(!empty($queue)){
$size = sizeof($queue);
$i = 0;
$answer = 0;
while($i<$size){
$i= $i+1;
//if first node print
if ($i == 1){
$answer += 1;
}
if($this->left){
array_push($queue, $this->left);
}
if($this->right){
array_push($queue, $this->right);
}
array_unshift($queue); //shift first item
}
} return $queue;
}
//calling function
function visibleNodes($root) {
// Write your code here
if(empty($root)){
return 0;
} else {
$answer = findLeft($root);
}
return $answer;
}

Linked list from user input php

public $head = null;
public $size = 0;
function push($value, $pos)
{
if($pos>0 && $pos>$this->size)
{
return false;
}
else{
$node = new Node($value);
if ( $pos == 0) {
$node->next=$this->head;
$this->head= $node;
$this->size++;
} else {
$current = $this->head;
for ($i = 0; $i < $pos; $i++) {
$previous = $current;
$current = $current->next;
}
$node->next = $current;
$previous->next = $node;
$this->size++;
}
}
}
function pop($pos)
{
$current=$this->head;
if($pos==0)
{
$this->head=$current->next;
}
else{
for($i=0;$i<$pos;$i++)
{
$previous=$current;
$current=$current->next;
}
$previous->next=$current->next;
}
$this->size--;
}
pushing value is working fine, but poping is not working,excuting pop() method and deleting value from database at the same time.stuck please help.
deleting value from database is easy but the order of linked list get unsorted and push method does not work.
deleting value of pos=0 will delete pos=0 from database and pos will start from pos=1 and push method is not excuting.

Heaviest path in special graph (PHP)

I have to search the heaviest path in graph what like:
1
2 1
4 5 8
2 2 3 4
(1,1,8,4 in this example)
The graph like this ever.
So it is an element who has two children except lowermosts. Who has children they has a common child e.g. (in above graph) 5 (in 3. row) is a common child to 2 and 1 (in 2. row.).
So these are nodes and not edges and them have a value.
I wrote an algorithm in php:
class node{
public $children = array();
public $value;
public $_heavier = null;
public $_value = null;
function __construct($value, $children) {
$this->value = $value;
$this->children = $children;
}
function heavier() {
if (null !== $this->_value) {
echo 'b' . $this->value . '<br>';
return $this->_value;
}
$val = $this->value;
if ($this->children[0]) {
$c1 = $this->children[0]->heavier();
$c2 = $this->children[1]->heavier();
if ($c1 > $c2) {
$this->_heavier = 0;
$val += $c1;
} else {
$this->_heavier = 1;
$val += $c2;
}
}
echo 'a' . $this->value . '<br>';
$this->_value = $val;
return $val;
}
function getPath() {
if (null !== $this->_heavier) {
echo $this->children[$this->_heavier]->getPath();
}
return $this->value;
}
}
$exists = array();
function a($row, $item) {
global $input, $exists;
$nextRow = $row + 1;
$child1No = $item;
$child2No = $item + 1;
$child1 = null;
if (isset($input[$nextRow][$child1No])) {
$child1 = a($nextRow, $child1No);
}
$child2 = null;
if (isset($input[$nextRow][$child2No])) {
$child2 = a($nextRow, $child2No);
}
if (!isset($exists[$row][$item])) {
$obj = new node($input[$row][$item], array($child1, $child2));
$exists[$row][$item] = &$obj;
} else {
$obj = &$exists[$row][$item];
}
return $obj;
}
$nodes = a(0, 0);
$nodes->heavier();
echo $nodes->getPath();
echo '<br>';
It is works, but too much time.
How to speed up?
Thx.
Your algorithm is the most optimal possible - you take O(n) time where n is the number of nodes. It can easily be proved that nothing faster can be done.
I think the slow part of your algorithm is the echo-ing - this is a very heavy operation and might slow your algorithm quite a bit as you echo too much.
PS: By the way on how many nodes you execute your algorithm? Is it really on only 10?

Insert node in the linklist at a specific index using PHP OOP

i want to Insert node in the linklist at a specific index using PHP OOP...
my code for insert node at the start and insert node at the end is the following
//top class for creating node
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
//main class which will insert node
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//insertion in start of linklist
public function insertFirst($data)
{
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
//insertion at the last of linklist
public function insertLast($data)
{
if($this->firstNode != NULL)
{
$link = new ListNode($data);
$this->lastNode->next = $link;
$link->next = NULL;
$this->lastNode = &$link;
$this->count++;
}
else
{
$this->insertFirst($data);
}
}
}
What you can do to keep OOP is create some methods on ListNode class like insertBeforeMe and insertAfterMe. As #Flame points, is not a LinkList bussines
Add this to ListNode
function addAtIndex($index, $data) {
if ($index != 0) {
//pass through links till you hit the index
$next->addAtIndex($index-1, $data)
} else {
$node = new ListNode($data);
$node->next = $this->next;
$this->next = &node;
}
}
Call like this:
$firstNode->addAtIndex($index, $data)
Not tested... just a thought
fixed it by the following code
public function insert($NewItem,$key){
if($key == 0){
$link = new ListNode($NewItem);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
else{
$link = new ListNode($NewItem);
$current = $this->firstNode;
$previous = $this->firstNode;
for($i=0;$i<$key;$i++)
{
$previous = $current;
$current = $current->next;
}
$previous->next = $link;
$link->next = $current;
$this->count++;
}
}

mysql_fetch_object is very slow takes about 30 seconds to load with only 20 ROWS [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simplest way to profile a PHP script
We are building this online application using MVC approach (but a bit tweeked).
The structure of the application goes like this.
class Page{
private $title;
private $css;
private $type;
private $formData;
private $obj;
public function __construct($type){
//this instance variable is designed to set form data which will appear on the pages
$this->formData = array();
$this->setup($type);
}
public function setTitle($var){
$this->title = 'Page : ';
$this->title .= $var;
}
public function getFormData() {
return $this->formData;
}
private function setFormData($tmpObjs) {
$finData = array();
foreach($tmpObjs as $value){
if($value == $this->obj && isset($_GET['new']))
$newValue = 'true';
else
$newValue = 'false';
$tmpData = array();
$tmpData = $value->getData($newValue);
$finData = array_merge($finData, $tmpData);
}
return $finData;
}
public function getTitle(){
return $this->title;
}
public function displayCSS($_SESSION){
$GlobalConfig = $_SESSION['Config'];
$CSS = array();
$CSS = $GlobalConfig->getCSS();
$SIZE = count($CSS);
foreach($CSS as $key => $value){
echo "<link href=\"".$CSS[$key]."\" type=\"text/css\" rel=\"stylesheet\" />\n";
}
}
public function displayJS($_SESSION){
$GlobalConfig = $_SESSION['Config'];
$JS = array();
$JS = $GlobalConfig->getJS();
$SIZE = count($JS);
foreach($JS as $key => $value){
echo "<script src=\"".$JS[$key]."\" type=\"text/javascript\"></script>\n";
}
}
function setPageType($type)
{
$this->type = $type;
}
// This is used when you are filtering whatever type for search function
function getPageType(){
$type = $this->type;
echo $type;
}
function setup($type){
$this->type = $type;
switch($this->type){
case "AccountExpiry":
break;
case "Home":
$CalendarExpiryItemList = new CalendarExpiryItemList();
$CalendarExpiryItemList->createList();
$_SESSION['Active_Form'] = 'homepage-record';
$this->obj = $CalendarExpiryItemList;
$objs = array($CalendarExpiryItemList);
$this->formData = $this->setFormData($objs);
$this->setTitle('Home');
break;
}
}
function generateJS(){
if(file_exists('../classes/Javascript.class.php'))
include_once '../classes/Javascript.class.php';
$JSType = str_replace(" " , "", ucwords(str_replace("-", " ", substr(end(explode("/", $_GET['page'])), 0, -4))));
$JSType = $_GET['page'];
if(substr($JSType, -1) == 's')
$JSType = substr ($JSType, 0, -1);
echo $JSType;
$new_obj_name = $JSType . "JS";
$jsObj = new $new_obj_name($this->type);
}
function getObject(){
return $this->obj;
}
//There is more code, file has been omitted for forum
}
The following is the CalendarExpiryItemList class
class CalendarExpiryItemList
{
private $List = array();
public function __construct()
{
//Nothing To Do Yet
}
public function createList($Type = "Followups")
{
switch($Type)
{
case "ALL":
$this->List = array();
$this->getAllItemsInArray();
return $this->List;
break;
case "Invoice":
$this->List = array();
$this->getInvoiceCalendarItems();
return $this->List;
break;
case "Followups":
$this->List = array();
$this->getFollowUpExpiryItems();
return $this->List;
break;
}
}
public function _compare($m, $n)
{
if (strtotime($m->getExpiryDate()) == strtotime($n->getExpiryDate()))
{
return 0;
}
$value = (strtotime($m->getExpiryDate()) < strtotime($n->getExpiryDate())) ? -1 : 1;
echo "This is the comparison value" . $value. "<br/>";
return $value;
}
public function display()
{
foreach($this->List as $CalendarItem)
{
echo "<tr>";
if($CalendarItem->getType() != "ContractorInsurance")
echo "<td>".DateFormat::toAus($CalendarItem->getExpiryDate())."</td>";
else
echo "<td>".$CalendarItem->getExpiryDate()."</td>";
echo "<td>".$CalendarItem->getType()."</td>";
echo "<td>".$CalendarItem->getDescription()."</td>";
echo "<td>".$CalendarItem->doAction()."</td>";
echo "</tr>";
}
}
public function getData()
{
$data = array();
$data['Rows'] = "";
$TempArray1 = array();
foreach($this->List as $CalendarItem)
{
$Temp = "";
$Temp .= "<tr>";
if($CalendarItem->getType() != "ContractorInsurance")
$Temp .= "<td>".DateFormat::toAus($CalendarItem->getExpiryDate())."</td>";
else
$Temp .= "<td>".$CalendarItem->getExpiryDate()."</td>";
$Temp .= "<td>".$CalendarItem->getType()."</td>";
$Temp .= "<td>".$CalendarItem->getDescription()."</td>";
$Temp .= "<td>".$CalendarItem->doAction()."</td>";
$Temp .= "</tr>";
$TempArray1[] = $Temp;
}
if(count($TempArray1) == 0)
{
$Row = "<tr><td colspan='4'>No Items overdue</td></tr>";
$TempArray1[] = $Row;
}
$data['Rows'] = $TempArray1;
return $data;
}
//---------------Private Functions----------------
private function SortArrayDate()
{
$TempArray = array();
$TempArray = $this->List;
$this->List = array();
foreach($TempArray as $CalendarItem)
{
$this->List[$CalendarItem->getExpiryDate()] = $CalendarItem;
}
ksort($this->List);
}
private function getAllItemsInArray()
{
$this->getInvoiceCalendarItems();
$this->getFollowUpExpiryItems();
$this->getProjectExpiryItems();
$this->getVehicleExpiryItems();
$this->getUserInsuranceExpiryItems();
$this->getContractorExpiryItems();
//$this->SortArrayDate();
}
private function getContractorExpiryItems()
{
$SQL = "SELECT * FROM `contractor_Details` WHERE `owner_id` =".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$InsLic = new ContractorInsLis();
$InsLic->getContractorInsLisById($row->contractor_id);
if($InsLic->CheckExpiry($InsLic->getwcic_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getwcic_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Workers Comp License expired on ".$InsLic->getwcic_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getpli_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getpli_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Public Liability Insurance expired on ".$InsLic->getpli_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getcontractor_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getcontractor_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Contractor License expired on ".$InsLic->getcontractor_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getwcic_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getcompany_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Company License expired on ".$InsLic->getcompany_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
}
}
private function getUserInsuranceExpiryItems()
{
$SQL = "SELECT * FROM `user_my_insurances_licences` WHERE `user_id`=".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$UserInsuranceLicenses = new UserMyLicenseInsurance();
if($UserInsuranceLicenses->CheckExpiry($row->DL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->DL_expiry_date,"DL #".$row->DL_number." has expired on ".$row->DL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->CL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->CL_expiry_date,"CL #".$row->CL_number." has expired on ".$row->CL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->BL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->BL_expiry_date,"BL #".$row->BL_number." has expired on ".$row->DL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->wcic_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->wcic_expiry_date,"Workers Compe #".$row->wcic_policy_number." has expired on ".$row->wcic_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->pli_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->pli_expiry_date,"Public Liability #".$row->pli_policy_number." has expired on ".$row->pli_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->cwi_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->cwi_expiry_date,"Contract Worker Insurance #".$row->cwi_policy_number." has expired on ".$row->cwi_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->hoi_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->hoi_expiry_date,"Home Owners Insurance #".$row->hoi_policy_number." has expired on ".$row->hoi_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->pii_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->pii_expiry_date,"Professional Indemnity Owners Insurance #".$row->pii_policy_number." has expired on ".$row->pii_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->tic_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->tic_expiry_date,"Tools Insurance #".$row->tic_policy_number." has expired on ".$row->tic_expiry_date);
$this->List[] = $ExpiredItem;
}
}
}
private function getVehicleExpiryItems()
{
$SQL = "SELECT * FROM `user_my_motor_vehicles` WHERE `user_id` =".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$UserMotorVehicles = new UserMotorVehicles();
if($UserMotorVehicles->CheckExpiry($row->vehicle_registration_expiry_date) == 'Expired')
{
$VehicleRegistration = new VehicleExpiryItem($row->id,$row->vehicle_registration_expiry_date,"Vehicle ".$row->vehicle_reg_no." Registration Expired on ".$row->vehicle_registration_expiry_date);
$this->List[] = $VehicleRegistration;
}
if($UserMotorVehicles->CheckExpiry($row->insurance_expiry_date) == 'Expired')
{
$VehicleInsurance = new VehicleExpiryItem($row->id,$row->insurance_expiry_date,"Vehicle ".$row->vehicle_reg_no." Insurace Expired on ".$row->insurance_expiry_date);
$this->List[] = $VehicleInsurance;
}
}
}
private function getProjectExpiryItems()
{
$SQL = "SELECT * FROM my_project WHERE user_id =".$_SESSION['user_id']." AND ((end_date < '".date('Y-m-d')."') OR (end_date = '".date('Y-m-d')."') OR end_date='0000-00-00') AND (actual_end_date = '' OR actual_end_date = ' ' OR actual_end_date = '0000-00-00')";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Project = new ProjectExpiryItem($row->project_id,$row->end_date,"Project ".$row->project_name." was due on ".$row->end_date,$row->start_date);
$this->List[] = $Project;
}
}
private function getInvoiceCalendarItems()
{
$SQL = "SELECT * FROM project_invoices WHERE (dueDate < '".date('Y-m-d')."') AND (date_paid ='0000-00-00' OR date_paid='') AND (user_id = ".$_SESSION['user_id'].") LIMIT 0, 10";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Invoice = new InvoiceExpiryItem($row->id,$row->invoice_date,"Invoice #".$row->id." is overdue.");
//testObj(array($Invoice));
$this->List[] = $Invoice;
}
}
private function getFollowUpExpiryItems()
{
$SQL = "SELECT * from followUps WHERE owner_id=".$_SESSION['user_id']." AND ((Date_Due < '".date('Y-m-d')."') OR (Date_Due = '".date('Y-m-d')."') OR (Date_Due = '0000-00-00')) AND Completed != '1'";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Form_Id = new FormId();
$Description = "Follow Up on ".$Form_Id->getFormNam($row->Form_id)." was due on ".$row->Date_Due;
$FollowUp = new FollowUpExpiryItem($row->Id,$row->Date_Due,$Description);
$this->List[] = $FollowUp;
}
}
This is the pagination Class
<?php
class Pagination {
protected $Items = array();
protected $Type = "default";
protected $Title = "List of ";
protected $Base_Url = "";
protected $Table;
//-------------------------Table Settings----------------//
protected $No_Of_Columns = NULL;
protected $No_Of_Items_Per_Page = 10; //By Default 10 items will be displayed on a page.protected
protected $Present_Page = 0;
protected $Columns = array();
protected $Rows = array();
//------------------------Table Class Attributes---------//
protected $Table_Class = "";
protected $Table_Id = "";
protected $GETVarName = "PP";
/**
*
*/
public function __construct()
{
$this->Table = false;
}
public function paginate()
{
//Check if the base url is set
if(strlen($this->Base_Url) == 0){
echo "Error: Could not paginate, No base url Found!";
}
//Set the Current page value to Present Page
if(isset($_GET))
{
if(isset($_GET[$this->GETVarName])){
$this->Present_Page = intval($_GET[$this->GETVarName]);
} else {
$this->Present_Page = 1;
}
}
//Draw the table and the values
$this->generatePaginationTable();
}
public function setData($data)
{
if(is_array($data)){
$this->Rows = $data;
return true;
} else {
return false;
}
}
public function putData($object,$functionName = "generateRow")
{
$TempData = array();
if(method_exists($object,"getObjs"))
{
$ObjectArray = $object->getObjs();
}
if(method_exists($object,$functionName))
{
foreach($ObjectArray as $Obj)
{
$TempData[] = $object->$functionName($Obj);
}
}
$this->setData($TempData);
unset($TempData);
}
public function setIsTable($val)
{
$this->IsTable = $val;
}
public function addColumnNames($Col){
if(is_array($Col)){
$this->No_Of_Columns = $Col;
} else {
return false;
}
}
/**
* #param $config (array)
* #return bool
*
* this function initializes the Pagination object with the
* initial values
*/
public function initialize($config)
{
if(is_array($config))
{
foreach($config as $key => $value)
{
if(isset($this->$key))
{
$this->$key = $value;
}
}
} else if(is_object($config)) {
return false;
} else if(is_string($config)){
return false;
}
}
//------------------------------Private Function For the Class-------------------------//
private function generatePaginationTable()
{
if($this->Table){
$this->StartTable();
$this->DisplayHeader();
}
$this->DisplayData();
$this->DisplayLinks();
if($this->Table)
echo "</table>";
}
private function DisplayLinks()
{
if($this->Table){
echo "<tr>";
echo '<td colspan="'. count($this->Rows) .'">';
$this->GenerateLinkCounting();
echo '</td>';
echo "</tr>";
} else {
if(count($this->Rows) > 0)
{
$ROW = $this->Rows[0];
$ColSpan = substr_count($ROW,"<td");
echo "<tr>";
echo '<td colspan="'. $ColSpan .'" align="right">';
$this->GenerateLinkCounting();
echo '</td>';
echo "</tr>";
}
}
}
private function GenerateLinkCounting()
{
$this->Base_Url .= $this->getOtherGetVar();
$StartCount = 1;
$EndCount = count($this->Rows) / $this->No_Of_Items_Per_Page;
for($i=0; $i < $EndCount; $i++)
{
if($i == 0)
{
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1). '" >First</a> ';
} else if($i == intval($EndCount)){
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1).'" >Last</a> ';
} else {
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1). '" >'.intval($i+1).'</a> ';
}
}
}
private function getOtherGetVar()
{
$Link = "";
if(isset($_GET))
{
foreach($_GET as $key => $val)
{
if($key != $this->GETVarName)
{
$Link .= "&".$key."=".$val;
}
}
}
$h = preg_split("/&/",$this->Base_Url);
$this->Base_Url = $h[0];
return $Link;
}
private function DisplayData()
{
$Index = 0;
$StartIndex = intval(intval($this->Present_Page-1) * $this->No_Of_Items_Per_Page);
$EndIndex = intval($StartIndex + $this->No_Of_Items_Per_Page);
foreach($this->Rows as $Row)
{
$Index++;
if($Index >= $StartIndex && $Index <= $EndIndex)
{
echo "<tr>";
if(is_array($Row))
{
foreach($Row as $key => $value){
echo "<td>".$value."</td>";
}
} else {
echo $Row;
}
echo "</tr>";
}
}
}
private function DisplayHeader()
{
if(is_array($this->Columns))
{
echo "<thead>";
echo "<tr>";
foreach($this->Columns as $Col => $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
echo "</thead>";
}
}
private function StartTable()
{
echo "<table ";
if(strlen($this->Table_Class) > 0)
echo 'class="'.$this->Table_Class.'" ';
if(strlen($this->Table_Id) > 0)
echo 'id="'.$this->Table_Id.'" ';
echo ">";
}
}
Final Implementation of the File
<?php
$Page = new Page('Home');
$data = $Page->getFormData();
$Pagination = new Pagination();
$config = array();
$config['Table'] = false;
$config['No_Of_Items_Per_Page'] = 25;
$config['Base_Url'] = base_url() . 'BootLoader.php?page=Homepage';
$config['GETVarName'] = "ODL";
$Pagination->initialize($config);
$Pagination->setData($data['Rows']);
/**
* Want to have multiple lists
*/
$CalendarExpiryList = $Page->getObject();
$CalendarExpiryList->createList("Invoice");
$InvoiceList = new Pagination();
$config = array();
$config['Table'] = false;
$config['No_Of_Items_Per_Page'] = 25;
$config['Base_Url'] = base_url() . 'BootLoader.php?page=Homepage';
$config['GETVarName'] = "OIDL";
$InvoiceList->initialize($config);
$data2 = $CalendarExpiryList->getData();
$InvoiceList->setData($data2['Rows']);
//This is the display
include_once("Forms/homepage/home-page.html.php");
?>
The PHP Script runs fine. It takes about 0.03 to load.
But when the script reaches the CalendarExpiryItemList class. It takes about 30 seconds and my server times out.
Each table would have around 12 to 15 fields on an average and about 10 to 100 records to go through.
I am on hosting with a hosting company they have load balancers. So if my scripts takes more than 30 seconds the load balancer resets my connection and return an error saying "Server sent no data"
As the others say you should try profile your code.
...without being able to debug the code, maybe one or more of the methods in CalendarExpiryItemList class is failing at some point either; on the query, or associated query, or returning a endless loop. You should test and debug each method individually on a your test server to see what results your getting. For a quick and dirty test, just log the output of each method to a file. Also check $_SESSION['user_id'] has a value and use ". (int) $_SESSION['user_id'] as well before sending it the db in case its empty because its not escaped.

Categories