Hello world I'm new so sorry for my question. but I need your help
I have this code
public function GetSyncTransaksi ($ip_add_Get,$DBIDGet='db_ique',$table_get='transaksi') {
$temp_get = NULL;
if ($DBIDGet == 'db_ique') {
$dbhost_get = $ip_add_Get;
$dbuser_get = USER_CABANG; //Harus diganti
$dbpwd_get = PASS_CABANG; //Harus diganti
$dbname_get = $DBIDGet;
} else {
$dbhost_get = $ip_add_Get;
$dbuser_get = USER_PUSAT; //Harus diganti
$dbpwd_get = PASS_PUSAT; //Harus diganti
$dbname_get = "ique_".$DBIDGet;
}
R::addDatabase($dbname_get, 'mysql:host='.$dbhost_get.';dbname='.$dbname_get, $dbuser_get, $dbpwd_get, TRUE);
R::selectDatabase($dbname_get);
$qget = "SELECT * FROM sync_$table_get";
$temp_get = R::getAll($qget);
return $temp_get;
}
public function UpdateSyncTransaksi ($ip_add,$DBID='db_ique',$table='transaksi') {
$temp = NULL;
if ($DBID == 'db_ique') {
$dbhost = $ip_add;
$dbuser = USER_CABANG;
$dbpwd = PASS_CABANG;
$dbname = $DBID;
} else {
$dbhost = $ip_add;
$dbuser = USER_PUSAT;
$dbpwd = PASS_PUSAT;
$dbname = "ique_".$DBID;
}
R::addDatabase($dbname, 'mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpwd, TRUE);
R::selectDatabase($dbname);
$q = "TRUNCATE TABLE sync_$table";
$temp = R::exec($q);
$q = "INSERT INTO sync_$table SELECT tanggal,COUNT(*) FROM $table GROUP BY tanggal";
$temp = R::exec($q);
return $temp;
}
And I call to this Function
public function CompareSyncTransaksi ($server,$id,$table='transaksi') {
$difference = NULL;
$updatesynccabang = $this->UpdateSyncTransaksi($server,'db_ique',$table); //Update sync_transaksi cabang
$updatesyncpusat = $this->UpdateSyncTransaksi("localhost",$id,$table); //Update sync_transaksi pusat
$synccabang = $this->GetSyncTransaksi($server,'db_ique',$table);
$syncpusat = $this->GetSyncTransaksi("localhost",$id,$table);
$tglcabang = NULL;
if ($synccabang != NULL) {
foreach ($synccabang as $temp) {
$tglcabang[] = $temp->tanggal;
}
}
$tglpusat = NULL;
if ($syncpusat != NULL) {
foreach ($syncpusat as $temp) {
$tglpusat[] = $temp->tanggal;
}
}
$intersect = NULL;
if($tglcabang != NULL && $tglpusat != NULL) {
$difference = array_diff($tglcabang,$tglpusat);
$intersect = array_intersect($tglcabang,$tglpusat);
}
if($intersect != NULL) {
foreach ($intersect as $temp) {
foreach ($synccabang as $temp1) {
if ($temp1->tanggal == $temp) {
$jumlahcabang = $temp1->jumlah;
}
}
foreach ($syncpusat as $temp2) {
if ($temp2->tanggal == $temp) {
$jumlahpusat = $temp2->jumlah;
}
}
if ($jumlahcabang != $jumlahpusat) {
$difference[] = $temp;
}
}
}
if ($difference) {
asort($difference);
}
return $difference;
}
The problem is I got Error "A database has already be specified for this key."
I think the problem is in function GetSyncTransaksi and function UpdateSyncTransaksi.
How can I fix this. please help thank you
Related
Introduction
Hi, I hope everyone is doing great. I am a little advance to beginner level in Laravel and developing a system where I have to use Instagram API to get all the data against different hashtags.
These hashtags could be 1, or 2, or even more. Here is the code that I am sharing, this code is taking too much time to run because of the nested loops in it. Can anyone who is expert share his/her knowledge and give me suggestions on how to improve this piece of code?
The code
public function getHastagMediaByID($token)
{
$client = new \GuzzleHttp\Client();
$event_hashtag = $this->event->hashtag;
$hashtagArray = explode(',', $event_hashtag);
$hashtagIdArray = array();
// dd($hashtagArray);
$count = 0;
$decodedInstagramDataApiResponse = null;
if (isset($hashtagArray)) {
$userIGAccounts = Event_Social_Post::where('event_id', $this->event->id)->where('platform', 'instagram')->get();
if ($userIGAccounts != null) {
foreach ($userIGAccounts as $userinstaAcc) {
try {
$userInstaAccId = $userinstaAcc->page_id;
$instagramUserDataApi = $client->request('GET', "https://graph.facebook.com/v12.0/$userInstaAccId?fields=username%2Cprofile_picture_url&access_token=$token");
$getInstagramDataApiResponse = $instagramUserDataApi->getBody()->getContents();
$decodedInstagramDataApiResponse[] = json_decode($getInstagramDataApiResponse, true);
foreach ($hashtagArray as $key => $hashtagValue) {
if (isset($hashtagValue) && $hashtagValue != "") {
try {
$hashtagValue = ltrim($hashtagValue);
$InstagramHashtagIdApi = $client->request('GET', "https://graph.facebook.com/v11.0/ig_hashtag_search?user_id=$userInstaAccId&q=$hashtagValue&access_token=$token");
$getInstagramHashTagApiResponse = $InstagramHashtagIdApi->getBody()->getContents();
$decodedInstagramHashTag = json_decode($getInstagramHashTagApiResponse, true);
$InstagramHashtagID = $decodedInstagramHashTag['data'][0]['id'];
$hashtagPostSearchApi = $client->request('GET', "https://graph.facebook.com/v11.0/$InstagramHashtagID/recent_media?user_id=$userInstaAccId&fields=id%2Crecent_type%2Ccomments_count%2Clike_count%2Ccaption%2Cmedia_url%2Cpermalink%2Cchildren{media_url}%2Ctimestamp&access_token=$token");
$getHashtagPostSearchApiApiResponse = $hashtagPostSearchApi->getBody()->getContents();
$decodedHashtagPostSearchResponse = json_decode($getHashtagPostSearchApiApiResponse, true);
$hashtagIdArray[] = $decodedHashtagPostSearchResponse;
// var_dump($hashtagIdArray);
$count++;
} catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
if (Auth::check()) {
Session::put('instagramException', 'true');
Session::put('instagramExceptionMessage', $responseBodyAsString);
}
continue;
}
}
}
} catch (ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
if (Auth::check()) {
Session::put('instagramException', 'true');
Session::put('instagramExceptionMessage', $responseBodyAsString);
}
continue;
}
}
if (count($hashtagIdArray) > 0) {
foreach ($hashtagIdArray as $key => $post) {
$userDataLoopIndex = 0;
if (count($post['data']) > 0) {
// dd($post['data']);
foreach ($post['data'] as $postDatum) {
if (isset($postDatum['children'])) {
foreach ($postDatum['children'] as $key => $childrenData) {
foreach ($childrenData as $childrenSingleton) {
// $childrenSingleton['media_url'];
$soc = new E_social_wall;
$soc->text = $postDatum['caption'] ?? ''; //->caption;
$soc->image = $childrenSingleton['media_url'] ?? ''; //->media_url;
$soc->platform = 'instagram';
if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
//dd($media['userData']);
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
} else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
$userDataLoopIndex = 0;
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
}
$soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
$soc->url = $childrenSingleton['media_url'] ?? ''; //->media_url;
$soc->event_id = $this->event->id;
$soc->is_hashtag = 1;
if ($soc->image != '' || $soc->url != '') {
$soc->save();
}
$count++;
}
}
} else {
$soc = new E_social_wall;
$soc->text = $postDatum['caption'] ?? ''; //->caption;
$soc->image = $postDatum['media_url'] ?? ''; //->media_url;
$soc->platform = 'instagram';
if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
//dd($media['userData']);
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
} else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
$userDataLoopIndex = 0;
if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
$soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
} else {
$soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
}
$soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
$userDataLoopIndex++;
}
$soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
$soc->url = $postDatum['media_url'] ?? ''; //->media_url;
$soc->event_id = $this->event->id;
$soc->is_hashtag = 1;
if ($soc->image != '' || $soc->url != '') {
$soc->save();
}
$count++;
}
}
}
}
}
return array('response' => $hashtagIdArray, 'userData' => $decodedInstagramDataApiResponse);
}
}
}
any suggestion or help would be great. Thank you all in advance.
I have an error message in a PHP application that keeps pointing to an Update failing but reports that my Select command is not granted.
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT
command denied to user 'vahejaba'#'localhost' for table 'actionitems'
This is the update method that is triggering a select grant invalid error on vahejaba#loalhost.
Why do I get a select error on update and why is my username incorrect (this is incorrect for some reason I believe that I causing the error)?
Please help.
database.php
class Database
{
private static $instance;
private $dbh;
private static $dbengine = 'mysql';
private $dbname;
private static $dbhost = 'localhost';
function __construct()
{
$this->dbname = "vahejaba_projectaim"; //str_replace('.projectaim.tools', '', $_SERVER['HTTP_HOST']); //Config::$dbname;
$dbhost = Database::$dbhost;
$dbengine = Database::$dbengine;
$username = Config::$username;
$password = Config::$password;
try
{
$this->dbh = new PDO("$dbengine:host=$dbhost;dbname=$this->dbname", $username, $password);
}
catch (PDOException $e)
{
die("Error in establishing connection to database!");
}
}
public function update($table, $colsVals=null, $whereVals=null)
{
$table = $this->getTable($table);
$columns = "";
$valuelist = array();
$values = "";
$params = array();
$where = $this->where($whereVals);
$wherestr = $where['wherestring'];
$whereParams = $where['params'];
$set = $this->set($colsVals);
$setVals = $set['set'];
$setParams = $set['params'];
$setValsString = $set['setvals'];
$vals = $set['vals'];
$params = array_merge($whereParams, $setParams);
if ($table !== FALSE)
{
try
{
$dbname = $this->dbname;
$sql = $this->dbh->prepare("UPDATE $table SET $setValsString WHERE $wherestr");
$sql->execute($setParams);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die('Update failed: '. $e->getMessage());
}
}
}
}
config.php
class Config
{
static $username = 'vahejaba_user';
}
manageActionItems.php
class ManageActionItems
{
private $db;
private $dbh;
private $userManager;
private $cols;
private $rowCount;
private $vals;
private $actionItemGrid;
private $requiredCols;
private $projectId;
private $table;
private $tool;
function __construct($excludeCols = array(), $requiredCols = array(), $projectId)
{
$this->db = Database::getInstance();
$this->userManager = new UserManager();
$this->dbh = $this->db->getHandle();
$this->table = 'ActionItems';
$this->tool = 'actionitem';
$this->requiredCols = $requiredCols;
$this->projectId = $projectId;
$this->actionItemGrid = new Grid($this->table, $excludeCols);
$this->cols = $this->actionItemGrid->getCols();
$this->rowCount = $this->actionItemGrid->getRowCount();
}
public function edit($id)
{
if (isset($_SESSION['errmsg']))
unset($_SESSION['errmsg']);
$ymdDueDate = "";
$ymdAssigned = "";
$ymdECD = "";
$ymdClosedDate = "";
$ymdCompletionDate = "";
$colsVals = array();
if (isset($_POST['editAssignedDate']) && $_POST['editAssignedDate'] != "" && $this->checkDate($_POST['editAssignedDate']))
{
$mdy = preg_split('/\//', $_POST['editAssignedDate']);
$ymdAssigned = "$mdy[2]-$mdy[0]-$mdy[1]";
}
else if (isset($_SESSION['AssignedDate']) && $_SESSION['AssignedDate'] != "")
{
$mdy = preg_split('/\//', $_SESSION['AssignedDate']);
$ymdAssigned = "$mdy[2]-$mdy[0]-$mdy[1]";
}
if (isset($_POST['editDueDate']) && $_POST['editDueDate'] != "" && $this->checkDate($_POST['editDueDate']))
{
$mdy = preg_split('/\//', $_POST['editDueDate']);
$ymdDueDate = "$mdy[2]-$mdy[0]-$mdy[1]";
}
else if (isset($_SESSION['DueDate']) && $_SESSION['DueDate'] != "")
{
$mdy = preg_split('/\//', $_SESSION['DueDate']);
$ymdDueDate = "$mdy[2]-$mdy[0]-$mdy[1]";
}
if (isset($_POST['editECD']) && $_POST['editECD'] != "" && $this->checkDate($_POST['editECD']))
{
$mdy = preg_split('/\//', $_POST['editECD']);
$ymdECD = "$mdy[2]-$mdy[0]-$mdy[1]";
}
else if (isset($_SESSION['ECD']) && $_SESSION['ECD'] != "")
{
$mdy = preg_split('/\//', $_SESSION['ECD']);
$ymdECD = "$mdy[2]-$mdy[0]-$mdy[1]";
}
if (isset($_POST['editClosedDate']) && $_POST['editClosedDate'] != "" && $this->checkDate($_POST['editClosedDate']))
{
$mdy = preg_split('/\//', $_POST['editClosedDate']);
$ymdClosedDate = "$mdy[2]-$mdy[0]-$mdy[1]";
}
else if (isset($_SESSION['ClosedDate']) && $_SESSION['ClosedDate'] != "")
{
$mdy = preg_split('/\//', $_SESSION['ClosedDate']);
$ymdClosedDate = "$mdy[2]-$mdy[0]-$mdy[1]";
}
if (isset($_POST['editCompletionDate']) && $_POST['editCompletionDate'] != "" && $this->checkDate($_POST['editCompletionDate']))
{
$mdy = preg_split('/\//', $_POST['editCompletionDate']);
$ymdCompletionDate = "$mdy[2]-$mdy[0]-$mdy[1]";
}
else if (isset($_SESSION['CompletionDate']) && $_SESSION['CompletionDate'] != "")
{
$mdy = preg_split('/\//', $_SESSION['CompletionDate']);
$ymdCompletionDate = "$mdy[2]-$mdy[0]-$mdy[1]";
}
$this->vals['AssignedDate'] = $ymdAssigned;
$this->vals['DueDate'] = $ymdDueDate;
$this->vals['ECD'] = $ymdECD;
$this->vals['CompletionDate'] = $ymdCompletionDate;
$this->vals['ClosedDate'] = $ymdClosedDate;
if (isset($_POST['editAssignedDate']))
$_SESSION['AssignedDate'] = $_POST['editAssignedDate'];
if (isset($_POST['editDueDate']))
$_SESSION['DueDate'] = $_POST['editDueDate'];
if (isset($_POST['editECD']))
$_SESSION['ECD'] = $_POST['editECD'];
if (isset($_POST['editCompletionDate']))
$_SESSION['CompletionDate'] = $_POST['editCompletionDate'];
if (isset($_POST['editClosedDate']))
$_SESSION['ClosedDate'] = $_POST['editClosedDate'];
$this->saveEditVals();
if($ymdAssigned != "" && $ymdDueDate != "" && $ymdAssigned > $ymdDueDate)
{
$_SESSION['errmsg'] = 'Due Date Must be Greater or Equal to Assigned Date';
return false;
}
else
{
unset($_SESSION['errmsg']);
}
foreach ($this->cols as $col)
{
if (array_key_exists($col, $_SESSION))
{
if($col != "ApproverID" && $col != "AltOwnerID" && $col != "OwnerID" && $col != "AssignorID" && $col != "AssignedDate" && $col != "DueDate" && $col != "ECD" && $col != "ClosedDate" && $col != "CompletionDate" && $col != "ID" && $col != "ActionItemID" && $col != "ProjectID")
$colsVals[$col] = $_SESSION[$col];
else if($col == 'AssignorID' && isset($_SESSION[$col]) && $_SESSION[$col] != 0)
$colsVals[$col] = intval($_SESSION[$col]);
else if($col == 'AltOwnerID' && isset($_SESSION[$col]) && $_SESSION[$col] != 0)
$colsVals[$col] = intval($_SESSION[$col]);
else if($col == 'OwnerID' && isset($_SESSION[$col]) && $_SESSION[$col] != 0)
$colsVals[$col] = intval($_SESSION[$col]);
else if($col == 'ApproverID' && isset($_SESSION[$col]) && $_SESSION[$col] != 0)
$colsVals[$col] = intval($_SESSION[$col]);
//else if ($col == 'AssignorID' || $col == 'AltOwnerID' || $col == 'ApproverID' || $col == 'OwnerID' && !isset($_SESSION[$col]))
// $colsVals[$col] = 'NULL';
}
}
// $manageLockedFields = new ManageLockedFields('actionitem');
$colsVals['AssignedDate'] = $ymdAssigned;
$colsVals['DueDate'] = $ymdDueDate;
$colsVals['ClosedDate'] = $ymdClosedDate;
$colsVals['CompletionDate'] = $ymdCompletionDate;
$colsVals['ECD'] = $ymdECD;
$where = array();
if ($id != null)
{
$where[] = array('Selector', '=', "'".substr($id, 0, 12)."'");
}
$this->db->update($this->table, $colsVals, $where);
return true;
}
In my database (phpmyadmin) I had a trigger that was incorrectly pointing to the wrong username and the wrong database name. After contacting the web host with no solution I investigated the trigger, uncovering the issue. Revision of the parameters eliminated the error.
Can you please help me to fully convert this class to work with mysqli?
It's a class working on an old system, I just want to make it work with mysqli without having to modify the existing code on all the system.
I tried but with no success.
Thanks in advance!
class BD {
var $sServidor = "host";
var $sBaseDeDatos = "DB";
var $sUsuario = "user";
var $sClave = "pass";
function Conectar() {
if (($this->sServidor != "") && ($this->sUsuario != "")) {
$this->oConexion = mysql_connect($this->sServidor, $this->sUsuario, $this->sClave);
mysql_select_db($this->sBaseDeDatos, $this->oConexion);
mysql_set_charset("utf8", $this->oConexion);
}
}
function RetornarConexion() {
return $this->oConexion;
}
function Seleccionar($pSQL, $pRetornarFila = false) {
$oResultado = $this->Ejecutar($pSQL);
return (($pRetornarFila) ? $this->RetornarFila($oResultado) : $oResultado);
}
function RetornarFila($pResultado) {
return mysql_fetch_array($pResultado);
}
function ContarFilas($pResultado) {
$lFilas = 0;
if ($pResultado) {
$lFilas = mysql_num_rows($pResultado);
}
return $lFilas;
}
function Ejecutar($pSQL) {
$this->Conectar();
$oResultado = mysql_query($pSQL, $this->oConexion);
if ($oResultado) {
if (strpos(strtoupper($pSQL), "INSERT INTO") !== false) {
$oResultado = mysql_insert_id();
} else if (strpos(strtoupper($pSQL), "UPDATE") !== false) {
$oResultado = mysql_affected_rows();
}
}
return $oResultado;
}
function RetornarTipo($pResultado, $pCampo) {
$sTipo = "";
if ($pResultado) {
$sTipo = mysql_field_type($pResultado, $pCampo);
}
return $sTipo;
}
function RetornarLongitud($pResultado, $pCampo) {
$lLongitud = 0;
if ($pResultado) {
$lLongitud = mysql_field_len($pResultado, $pCampo);
}
return $lLongitud;
}
function Desconectar() {
mysql_close($this->oConexion);
}
}
Okay I'm testing it and think it works okay. Here's the code:
P / D: Sorry for wasting your time. Conclusion: I have to sleep a few more hours per day. Thanks and sorry again.
class BD {
var $sServidor = "host";
var $sBaseDeDatos = "DB";
var $sUsuario = "user";
var $sClave = "pass";
function Conectar() {
if (($this->sServidor != "") && ($this->sUsuario != "")) {
$this->oConexion = mysqli_connect($this->sServidor, $this->sUsuario, $this->sClave);
mysqli_select_db($this->oConexion, $this->sBaseDeDatos);
mysqli_set_charset($this->oConexion, "utf8");
}
}
function RetornarConexion() {
return $this->oConexion;
}
function Seleccionar($pSQL, $pRetornarFila = false) {
$oResultado = $this->Ejecutar($pSQL);
return (($pRetornarFila) ? $this->RetornarFila($oResultado) : $oResultado);
}
function RetornarFila($pResultado) {
return mysqli_fetch_array($pResultado);
}
function ContarFilas($pResultado) {
$lFilas = 0;
if ($pResultado) {
$lFilas = mysqli_num_rows($pResultado);
}
return $lFilas;
}
function Ejecutar($pSQL) {
$this->Conectar();
$oResultado = mysqli_query($this->oConexion, $pSQL);
if ($oResultado) {
if (strpos(strtoupper($pSQL), "INSERT INTO") !== false) {
$oResultado = mysqli_insert_id($this->oConexion);
} else if (strpos(strtoupper($pSQL), "UPDATE") !== false) {
$oResultado = mysqli_affected_rows($this->oConexion);
}
}
return $oResultado;
}
function RetornarTipo($pResultado, $pCampo) {
$sTipo = "";
if ($pResultado) {
$sTipo = mysqli_field_type($pResultado, $pCampo);
}
return $sTipo;
}
function RetornarLongitud($pResultado, $pCampo) {
$lLongitud = 0;
if ($pResultado) {
$lLongitud = mysqli_field_len($pResultado, $pCampo);
}
return $lLongitud;
}
function Desconectar() {
mysqli_close($this->oConexion);
}
}
HI Guys I have A problem I want to upload csv files and store to database
But doesn't work..
I tried to debug it several times but not working hope you help me guys.
I Have a csv file containing..
firstname lastname middlename gender
test test test male
Then when I upload this csv file doesn't work.
This is my code..
<?php
session_start();
include ("config.php");
$extension = end(explode(".",basename($_FILES['file']['name'])));
if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension== 'csv')
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
try
{
$connection = new pdo("mysql:host=$hostname;dbname=upload",$username,$password);
if
$upload = $connection->prepare("INSERT INTO tbl_upload(firstname,lastname,middlename,gender)
VALUES (?,?,?,?)");
if($handle !== false)
{
fgets($handle);
while (($data = fgetcsv($handle, 10000, ',') !== false))
{
$upload->execute($data);
}
fclose($handle);
$connection = null;
echo "<p class='bg-success'>Upload Success</p>";
header ("location: index.php");
}
}
catch(pdoExecption $e)
{
die($e->getmessage());
}
}
else
{
header("location:config.php");
}
?>
thanks for the help..
Your method is not viable.
To import CSV you can either use the mysqlimport utility or you have to split the csv records in separate fields to match your INSERT statement. You cannot just feed CSV to the insert statement and hope that it sorts out things for itself.
I can give you a little CsvImport class I wrote some time ago make importing CSV a little bit easier
<?php
final class CsvImport {
private $file = "";
private $fields = array(); //array("field1", "field2", "field3"); ...
private $data = array(); //array([1] => array("value", "value", "value") ...
private $delimiter = "";
private $fieldCount = 0;
private $rowCount = 0;
private $internalCounter = 0;
private $loaded = false;
public function __construct($_file, $_delimiter = "") {
$this->file = $_file;
if(is_file($this->file) == true) {
if(($handle = fopen($this->file, "r")) !== false) {
//If the delimiter is not set try to suggest it
if(strlen($_delimiter) == 0) {
$this->delimiter = $this->suggestDelimiter();
} else {
$this->delimiter = $_delimiter;
}
if(strlen($this->delimiter) > 0) {
$row = 0;
while(($data = fgetcsv($handle, 0, $this->delimiter)) !== false) {
if($row == 0) {
$this->fieldCount = count($data);
}
if($this->fieldCount > 0) {
for($c = 0; $c < $this->fieldCount; $c++) {
if($row == 0) {
$this->fieldCount = count($data);
$this->fields[] = $data[$c];
} else {
$this->data[$row][$this->fields[$c]] = utf8_encode($data[$c]);
}
}
}
$row++;
}
$this->rowCount = $row;
if($this->fieldCount > 0) {
$this->loaded = true;
}
}
}
}
}
public function getNextRow() {
$retVal = false;
if($this->loaded == true) {
if($this->internalCounter < $this->rowCount) {
$this->internalCounter++;
$retVal = true;
} else {
$this->internalCounter = 0;
}
}
return $retVal;
}
public function readField($field) {
$retVal = false;
if($this->isLoaded() == true) {
if(isset($this->data[$this->internalCounter][$field]) == true) {
$retVal = $this->data[$this->internalCounter][$field];
}
}
return $retVal;
}
public function resetInternalCounter() {
$this->internalCounter = 0;
}
public function getFieldCount() {
return $this->fieldCount;
}
public function getRowCount() {
return $this->rowCount;
}
public function getFieldList() {
return $this->fields;
}
public function getDelimiter() {
return $this->delimiter;
}
public function isLoaded() {
return $this->loaded;
}
private function suggestDelimiter() {
$retVal = "";
$file = fopen($this->file, 'r');
$content = fgets($file);
fclose($file);
if(strlen($content) > 0) {
$list = array(
"," => substr_count($content, ","),
"." => substr_count($content, "."),
"&" => substr_count($content, "&"),
"%" => substr_count($content, "%"),
"-" => substr_count($content, "-"),
";" => substr_count($content, ";"),
"'" => substr_count($content, "'"),
"\"" => substr_count($content, "\""),
);
$maxCount = 0;
foreach($list as $key => $value) {
if($value > 0) {
if($value > $maxCount) {
$retVal = $key;
$maxCount = $value;
}
}
}
}
return $retVal;
}
private function __clone() { }
}
?>
The usage is as simple as this:
$file = "/path/to/file.csv";
$import = new CsvImport($file);
if($import->isLoaded() == true) {
while($import->getNextRow()) {
foreach($import->getFieldList() as $fieldName) {
$value = $import->readField($fieldName);
echo $fieldName . " => " . $value . "<br />";
}
}
}
I am sure you can build your queries with all field names in the foreach loop and fire each query in the while loop.
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.