PHP PDO Pagination not refreshed - php

im quite new to PHP and im trying to make a pagination, the code works! but i need to click on the button twice to make the page refreshed/change. how do i fix this?
view/main/user/userlist.php
<?php
$_SESSION['pagelim'] = 10;
$_SESSION['page'] = $_GET['halaman'];
if ($_SESSION['page'] == '') {
$_SESSION['pos'] = 0;
$_SESSION['page'] = 1;
} else {
$_SESSION['pos'] = ($_SESSION['page']- 1) * $_SESSION['pagelim'];
}
$itemcount = listpetugas::getlisted();
$pagecount = ceil(listpetugas::getlisted()/$_SESSION['pagelim']);
for ($i=1;$i<=$pagecount;$i++)
{ ?>
<?php
if ($i!=$pagecount){
echo " <ul class='pagination'><li><a href='?controller=main&action=userlist&halaman=$i' onclick='myFunction()'>$i</a></li></ul>";?>
<?php }
else{
echo "$i";
} ?>
<?php } ?>
model/userdb.php
public static function listemup()
{
if ($_SESSION['pos'] =='' && $_SESSION['pagelim'])
{
$pos = 0;
$lim = 10;
}
else {
$pos = $_SESSION['pos'];
$lim = $_SESSION['pagelim'];
}
$list = [];
$db = FirstFire::StartConnection();
$req = $db->query("SELECT * FROM randomity LIMIT $pos,$lim");
$rowcount = $req->rowCount();
foreach ($req->fetchAll() as $post) {
$list[] = new listpetugas($post['name'],$post['email'],$post['adress'],$post['wow']);
}
return $list;
}
JS
<script>
function myFunction() {
location.reload();
}
</script>
sorry for the messy code.

Related

How to write poll data to a text file? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Im trying to make a poll in php. Im trying to gather data by writing the info to a txt file. How do I get the code to write the data to a txt file?
This all the code I have in my handler, how do I make it write to my txt file. Most of the stuff at the bottom doesn't matter yet. Try to look at the code that say if ($submit == 'submit') and what follows that.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Poll</title>
</head>
<body>
<?php
//no need for sport validation is unimportant and doesnt work
if (isset($_REQUEST['Soda'])) {
$Soda = $_REQUEST['Soda'];
} else {
$Soda = NULL;
echo '<p class="error">You forgot to select your favorite soda!</p>';
}
//This is end of soda validation
if (!empty($_REQUEST['Book'])) {
$Book = $_REQUEST['Book'];
} else {
$Book = NULL;
echo '<p class="error">You forgot to write in your favorite book!</p>';
}
//End of book validation
if (isset($_REQUEST['SOTU'])) {
$SOTU = $_REQUEST['SOTU'];
} else {
$SOTU = NULL;
echo '<p class="error">You forgot to select the two biggest issues of the state of the union address!</p>';
}
//End of SOTU validation
if (isset($_REQUEST['Soda']) && !empty($_REQUEST['Book']) && isset($_REQUEST['SOTU'])) {
echo' Thank You for filling out the survey!<br> You can see the results of the pole' . " here!<br><br> Your response has been recorded.";
} else {
echo '<p class="error">Please go ' . "back" . ' and fill out the poll!<p>';
}
//End of link responses
//Define variables and make sure file works
$submit = $_REQUEST['submit'];
$filename = 'poll_data.txt';
$handle = fopen($filename, 'a');
//next is the stuff that is to be appended
if ($submit == 'Submit') {
fopen($filename, 'w');
$newdata = $Soda . PHP_EOL;
fwrite($handle, $newdata);
} else { echo 'You didn\'t click submit';}
//Now to sort the data and present it
/*explode('PHP.EOL', $filename);
$CC = 0;
$P = 0;
$MD = 0;
$SS = 0;
$BR = 0;
$DLS = 0;
$O = 0;
foreach($filename as $value) {
if ($value = 'Coca-Cola') {
$CC = $CC + 1;
}
elseif ($value = 'Pepsi') {
$P = $P + 1;
}
elseif ($value = 'MtnDew') {
$MD = $MD + 1;
}
elseif ($value ='Sprite/Sierra-Mist') {
$SS = $SS + 1;
}
elseif ('BigRed') {
$BR = $BR + 1;
}
elseif ('DontLikeSoda') {
$DLS = $DLS + 1;
}
elseif ('Other') {
$O = $O + 1;
}
}*/
?>
this should work:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Poll</title>
</head>
<body>
<?php
//no need for sport validation is unimportant and doesnt work
if (isset($_REQUEST['Soda'])) {
$Soda = $_REQUEST['Soda'];
} else {
$Soda = NULL;
echo '<p class="error">You forgot to select your favorite soda!</p>';
}
//This is end of soda validation
if (!empty($_REQUEST['Book'])) {
$Book = $_REQUEST['Book'];
} else {
$Book = NULL;
echo '<p class="error">You forgot to write in your favorite book!</p>';
}
//End of book validation
if (isset($_REQUEST['SOTU'])) {
$SOTU = $_REQUEST['SOTU'];
} else {
$SOTU = NULL;
echo '<p class="error">You forgot to select the two biggest issues of the state of the union address!</p>';
}
//End of SOTU validation
if (isset($_REQUEST['Soda']) && !empty($_REQUEST['Book']) && isset($_REQUEST['SOTU'])) {
echo' Thank You for filling out the survey!<br> You can see the results of the pole' . " here!<br><br> Your response has been recorded.";
} else {
echo '<p class="error">Please go ' . "back" . ' and fill out the poll!<p>';
}
//End of link responses
//Define variables and make sure file works
$submit = $_REQUEST['submit'];
$filename = 'poll_data.txt';
//next is the stuff that is to be appended
if ($submit == 'Submit') {
$handle = fopen($filename, 'a');
fputs($handle, $Soda.PHP_EOL);
fclose($handle);
} else { echo 'You didn\'t click submit';}
//Now to sort the data and present it
/*explode('PHP.EOL', $filename);
$CC = 0;
$P = 0;
$MD = 0;
$SS = 0;
$BR = 0;
$DLS = 0;
$O = 0;
foreach($filename as $value) {
if ($value = 'Coca-Cola') {
$CC = $CC + 1;
}
elseif ($value = 'Pepsi') {
$P = $P + 1;
}
elseif ($value = 'MtnDew') {
$MD = $MD + 1;
}
elseif ($value ='Sprite/Sierra-Mist') {
$SS = $SS + 1;
}
elseif ('BigRed') {
$BR = $BR + 1;
}
elseif ('DontLikeSoda') {
$DLS = $DLS + 1;
}
elseif ('Other') {
$O = $O + 1;
}
}*/
?>
I think if you use
fopen($filename, 'r');
that should work.
http://www.php.net/manual/en/function.fopen.php

MySQLi Rows Not Loading

i have a basic form that loads 15 dropdown boxes with the same topics in each box. this is a voting page where the user can vote for his favorite topic or his least favorite topic. the problem i have is that the topics arent being loaded when i tell them to. Here is my code.
PHP
<?php
$Vote = new Vote();
class Vote {
public function GetTopic() {
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Query = 'SELECT * FROM Topics';
if($Gather = $Connect->query($Query))
{
while($Row = $Gather->fetch_assoc())
{
$Topic = $Row['Topic'];
echo '<option>'.$Topic.'</option>';
}
$Gather->free();
}
else
{
echo 'Error';
}
$Connect->close();
}
public function LoadTopic() {
for($I = 15; $I > 0; $I--)
{
echo '<select><option>'.$I.'</option>'.$this->GetTopic().'</select>';
}
}
}
?>
If you use your function like this you should return your html-data instead of outputting it:
public function GetTopic() {
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Query = 'SELECT * FROM Topics';
if($Gather = $Connect->query($Query))
{
$html = "";
while($Row = $Gather->fetch_assoc())
{
$Topic = $Row['Topic'];
$html .= '<option>'.$Topic.'</option>';
}
$Gather->free();
return $html;
} else
{
//handle error
}
$Connect->close();
}
Let's try something a bit more appropriate for a class:
<?php
class Vote
{
private $connect;
public $topics = array();
public function __construct()
{
$this->connect = new mysqli( '127.0.0.1', 'root', '', 'Data' );
if( $this->connect->connect_errno )
{
echo "Error:(" . $this->connect->connect_errno . "): " . $this->connect->connect_error . ".";
}
}
public function GetTopics()
{
$Query = 'SELECT * FROM Topics';
if( $Gather = $this->connect->query( $Query ) )
{
while( $Row = $Gather->fetch_assoc() )
{
$this->topics[] = $Row['Topic'];
}
$Gather->free();
}
else
{
echo 'Error';
}
}
public function LoadTopics()
{
if( $max = count($this->topics) > 0 )
{
$html = "<select>\r\n";
for( $i = 0; $i < $max; ++$i )
{
$html .= "<option value=" . $i . ">" . $this->topics[$i] . "</option>";
}
$html .= "</select>\r\n";
return $html;
}
else
{
return false;
}
}
public function __destruct()
{
$this->connect->close();
}
}
?>
The __construct() / __destruct() methods are practically made to put your connection in. You could have also combined both functions and just have the GetTopics() method (I compulsively changed some method and property names) run the query, format the results and return the $html.
Also, I upgraded your for function, in case you decide to add another entry later to your topics, it will expand with it instead of it counting through 15 static rows.
You can call it with:
<?php
$vote = new Vote();
echo $vote->GetTopics()->LoadTopics();
?>
I saw the answer was already selected, didn't want my work to go to waste though ;D
Alternate GetTopics() function, all rolled into one.
public function GetTopics()
{
$Query = 'SELECT * FROM Topics';
if( $Gather = $this->connect->query( $Query ) )
{
$html = "<select>\r\n";
$i = 0;
while( $Row = $Gather->fetch_assoc() )
{
$html .= "<option value=" . $i . ">" . $Row['Topic'] . "</option>";
++i;
}
$html .= "</select>\r\n";
$Gather->free();
return $html;
}
else
{
return "Error: No Results Returned";
}
}
And now it's just called by:
<?php echo $vote->GetTopics(); ?>

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.

set maximum of items that you can make in function

How can I say in/with the follow (see below) function that you can make max 3 items? And if you will make more than three items the function will stop and you get a warning?
function addSection() {
global $compid;
$sectionOb = new Item();
$sectionOb->i_id_pk = $sectionOb->newId();
$sectionOb->i_mod_comp_id_fk = $compid;
$sectionOb->c_titel = '';
$sectionOb->c_content = '';
$sectionOb->i_sort = $sectionOb->newSort($compid);
$sectionOb->insert();
}
if($action == 'add') {
addSection();
}
<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&action=add" />new section</a>
Use a static counter variable:
function limited() {
static $invocationcount = 0;
++$invocationcount;
if($invocationcount <= 3) {
echo "You have called this function $invocationcount times.";
}
else {
echo "Stop doing that!";
}
}
See it in action.
If you are not too concerned about URL spoofing, I would add a counter variable in the URL which is passed to the addSection() method like so:
function addSection($count) {
if ($count >= 3) { return $count; }
global $compid;
$sectionOb = new Item();
$sectionOb->i_id_pk = $sectionOb->newId();
$sectionOb->i_mod_comp_id_fk = $compid;
$sectionOb->c_titel = '';
$sectionOb->c_content = '';
$sectionOb->i_sort = $sectionOb->newSort($compid);
$sectionOb->insert();
// Return incremented count
return $count + 1;
}
// Retrieve the last count from the URL
$count = isset($_GET['count']) ? intval($_GET['count']) : 0;
// Increment the count if the action is add and the addSection method suceedes
if($action == 'add') {
$count = addSection($count);
}
// Add count to the URL so we know what it is
<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&action=add&count=<?php echo $count; ?>" />new section</a>
Thanks a lot for help!! I have do it as follow:
function limit() {
global $compid;
$i = 0;
++$i;
$a_all = page1::page2Id($compid);
$i = sizeof($a_all);
if($i <= 2) {
$sectionOb = section();
$sectionOb->i_id_pk = $sectionOb->newId();
$sectionOb->i_mod_comp_id_fk = $compid;
$sectionOb->c_titel = '';
$sectionOb->c_content = '';
$sectionOb->i_sort = $sectionOb->newSort($compid);
$sectionOb->insert();
return true;
}
else {
return false;
}
}

jQuery & PHP and MYSQL IE Problem

Now All of this code works fine in Firfox but in IE the divs dont change when the php infomation changes.
Can some one help me please as i am working on a project and this is holding me back
Thank you.
Here is the jQuery Code:
$.ajaxSetup({ cache: false });
$(document).ready(function(){
$("#not").css('display','none');
$("#fonline").css('display','none');
$("#not").hide();
$("#fonline").hide();
$("#shfm").click(function () {
$("#not").hide();
$("#fonline").toggle();
});
$("#notifi").click(function () {
$("#fonline").hide();
$("#not").toggle();
});
});
function closeboxes() {
$("#fonline").hide();
$("#not").hide();
}
function loadContent(id) {
$("#contentArea").load("notifications.php?o="+id+"");
};
$(document).ready(function() {
$("#settings").toggle(
function () {
$(this).html('X Close');
},
function () {
$(this).html('Settings');
}
);
});
function FriendsContent(id) {
$("#fArea").load("friends_online.php?fo="+id+"");
};
$(document).ready(function() {
$("#Options").toggle(
function () {
$(this).html('X Close');
},
function () {
$(this).html('Options');
}
);
});
var refreshId = setInterval(function()
{
$('#fArea').fadeOut("slow").load('response.php').fadeIn("slow");
}, 10000);
PHP Code:
$cOption = $_GET['fo'];
switch($cOption) {
case 1:
$recordsPerPage = 5;
$pageNum = 1;
if(isset($_GET['pg'])) {
$pageNum = $_GET['pg'];
settype($pageNum, 'integer');
}
echo "<table width='98%' border='0' cellspacing='0' cellpadding='0'>";
$offset = ($pageNum - 1) * $recordsPerPage;
$onlineresult = mysql_query("SELECT * FROM online") or die (mysql_error());
while ($ousers = mysql_fetch_array($onlineresult)) {
$onuid = $ousers['uid'];
$flist = mysql_query("SELECT * FROM friends_list WHERE fid='$onuid' AND uid='$myid' LIMIT $offset, $recordsPerPage;") or die (mysql_error());
while ($fri = mysql_fetch_array($flist)) {
$id = $fir['id'];
$uid = $fri['uid'];
$fid = $fri['fid'];
$userinfomation = mysql_query("SELECT * FROM accounts WHERE id='$fid'");
$userinfo = mysql_fetch_array($userinfomation);
$v_tgid = $userinfo['tgid'];
echo "
<tr class='menutxt2'>
<td width='11%' height='21'><center>
</center></td>
<td width='50%'>$v_tgid</td>
<td width='39%'>View Profile</td>
</tr>
";
}
}
echo "</table>";
$query = "SELECT COUNT(id) AS id FROM friends_list;";
$result = mysql_query($query) or die('Mysql Err. 2');
$row = mysql_fetch_assoc($result);
$numrows = $row['id'];
$maxPage = ceil($numrows/$recordsPerPage);
$nav = '';
for($page = 1; $page <= $maxPage; $page++)
{
if ($page == $pageNum)
{
$nav .= "<span class='menutxt'>Pages: $page </span>";
}
else
{
$nav .= "";
}
}
if ($pageNum > 1) {
$page = $pageNum - 1;
$prev = "";
$first = "";
}
else {
$prev = '';
$first = '';
}
if ($pageNum < $maxPage) {
$page = $pageNum + 1;
$next = "";
$last = "";
}
else {
$next = '';
$last = '';
}
echo "$first <b>$prev</b> $nav<b> $next</b> $last";
echo "
";
break;
case 2:
echo 'Options';
break;
default:
echo 'Whoops, didn\'t understand that option: <i>'.$cOption.'</i>';
}
IE tends to cache ajax requests when you don't want it to. The .load() towards the end of your code is issuing a GET request which IE is probably caching instead of fetching from the server.
http://www.sitecrafting.com/blog/ajax-ie-caching-issues/
google search 'ie cache ajax jquery'

Categories