PHP Simple object oriented application - php

I am getting undefined variable for periods and subPeriods on the last line of this program. not sure what the problem is. Could it be my instances?
This is my first proper attempt at oop in PHP so i am sure i am doing something wrong.
$global_periods = 5;
$global_subperiods = 2;
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number)
{
$this->userId = $number;
}
public function addPeriod($pno)
{
$periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$answers[] = new Answer($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[] = new User($row['user_ref']);
}
for ($i = 0; $i >= count($userlist); $i++)
{
for ($x = 1; $x > $global_periods; $x++)
{
$userlist[i]->addPeriod($x);
for ($y = 1; $y > $global_subperiods; $y++)
{
$userlist[i]->$periods[x]->addSubPeriod($y);
foreach($questionslist as $aquestion)
{
$sql = 'SELECT ' . $questionNumber . ' FROM _survey_1_as WHERE user_ref = ' .
$i . ' AND answer_sub_period = ' . $y . ' AND answer_period = ' . $x .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[i]->$periods[x]->$subPeriods[y]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->$periods[2]->$subPeriods[2]->getAnswer();

Remove all the $ signs behind the $userlist, you only need to define the first variable. You can't use dollar signs like this, this way, it will try get the value of the word after the $ sign and call that, but that variable doesn't exist.

Related

Prepared Statements not working in mySQL / PHP [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
For some reason I keep getting this error when attempting to run prepared query with mysqli
mysqli_stmt::bind_result(): Number of bind variables doesn't match
number of fields in prepared statement
This db class works fine until I try to use a query with LEFT OUTER JOIN
I'm wondering if anyone knows why? I'll post the query, schema, etc.. below.
NOTE: I saw one question on here that suggested I specifically spell out all the field names I want to select, rather than use '*'(star). There are A LOT of fields involved and I spent almost an hour typing them all out. When I tested, it didn't change anything. I have omitted that and returned to using star just in case anyone was going to suggest I type them all out. Already tried. Doesn't help.
ALSO: This query works fine if I put it straight into phpMyAdmin, so it's a working query. Just throwing an error when trying to bind the result for some reason. Even if I remove the multiple joins and just have one left join it still throws the error about not having the correct parameter count. I don't get it.
Query Output by PHP
SELECT * FROM `SlipMaster`
left outer join `SlipMain`
on `SlipMaster`.`slipCode` = `SlipMain`.`slipCode`
left outer join `ContractMain`
on `SlipMain`.`slipContractId` = `ContractMain`.`id`
left outer join `ClientMain`
on `SlipMain`.`slipClientId` = `ClientMain`.`id`
left outer join `PaymentMain`
on `ContractMain`.`contractPaymentId` = `PaymentMain`.`id`
left outer join `VesselMain`
on `SlipMain`.`slipVesselId` = `VesselMain`.`id`
WHERE 1 = ?
PHP CODE USING MYSQLI DB CLASS
$from = '
`SlipMaster`
left outer join `SlipMain`
on `SlipMaster`.`slipCode` = `SlipMain`.`slipCode`
left outer join `ContractMain`
on `SlipMain`.`slipContractId` = `ContractMain`.`id`
left outer join `ClientMain`
on `SlipMain`.`slipClientId` = `ClientMain`.`id`
left outer join `PaymentMain`
on `ContractMain`.`contractPaymentId` = `PaymentMain`.`id`
left outer join `VesselMain`
on `SlipMain`.`slipVesselId` = `VesselMain`.`id`';
$dbi->new_query();
$dbi->add_param('i', '1');
$dbi->select($from, '*', '1=?');
PHP MYSQLI DB CLASS
<?php
class mysqliObject {
public $user = "";
public $pass = "";
public $name = "";
public $host = "";
public $_db;
public $_config;
public $MYSQLI_LINK = FALSE;
public $rows = FALSE;
public $last_error = FALSE;
public $last_query = FALSE;
public $result = FALSE;
public $last_id = FALSE;
public $paramTypeArray = [];
public $paramBindArray = [];
public function __construct() {
}
public function __destruct() {
$this->close();
}
public function connect() {
$this->host = $this->_config->get('DBHOST');
$this->name = $this->_config->get('DBNAME');
$this->user = $this->_config->get('DBUSER');
$this->pass = $this->_config->get('DBPASS');
$this->MYSQLI_LINK = new mysqli($this->host, $this->user, $this->pass, $this->name);
}
public function setDatabase($databaseConnection) {
$this->_db = $databaseConnection;
}
public function setConfig($config) {
$this->_config = $config;
}
public function close() {
#mysqli_close($this->MYSQLI_LINK);
}
public function get_hash($p) {
return password_hash($p, PASSWORD_BCRYPT, array("cost" => 10));
}
public function check_password($p, $h) {
return (password_verify($p, $h)) ? true : false;
}
public function get_rndkey($length=32) {
$random_string="";
while(strlen($random_string)<$length && $length > 0) {
$randnum = mt_rand(0,61);
$random_string .= ($randnum < 10) ?
chr($randnum+48) : ($randnum < 36 ?
chr($randnum+55) : $randnum+61);
}
return $random_string;
}
public function escape($value) {
return mysqli_real_escape_string($this->MYSQLI_LINK, $value);
}
public function get_lastid() {
return $this->MYSQLI_LINK->insert_id;
}
public function new_query() {
$this->paramTypeArray = Array();
$this->paramBindArray = Array();
}
public function add_param($t, $d) {
$this->paramTypeArray[] = $t;
$this->paramBindArray[] = $d;
}
// Shortcut for Select Method
public function s($t,$x, $d, $w) {
$this->new_query();
foreach($d as $v) {
$this->add_param($v['t'], $v['v']);
}
return $this->select($t, $x, $w) ? $this->result : false;
}
public function select($t, $d, $c) {
/* Types: s = string, i = integer, d = double, b = blob */
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$q = 'SELECT '.$d.' FROM '.$t.' WHERE '.$c;
$s = $this->MYSQLI_LINK->prepare($q);
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$meta = $s->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
call_user_func_array(array($s,'bind_result'),$fields);
$i = 0;
while ($s->fetch()) {
$results[$i] = [];
foreach($fields as $k => $v) {
$results[$i][$k] = $v;
}
$i++;
}
$s->close();
$this->last_query = $q;
if (count($results) > 0) {
$this->result = $results;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
return FALSE;
}
public function delete($t, $c) {
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$q = "delete from ".$t." where ".$c;
$s = $this->MYSQLI_LINK->prepare($q);
$this->last_query = $q;
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$count = $s->affected_rows;
$s->close();
if ($count > 0) {
$this->rows = $count;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
}
public function insert($t, $d) {
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$query_cols = 'insert into '.$t.' (';
$query_vals = 'values (';
while (list($key, $value) = each($d)) {
$query_cols .= $value . ', ';
$query_vals .= '?, ';
}
$query_cols = substr($query_cols, 0, strlen($query_cols) - 2);
$query_vals = substr($query_vals, 0, strlen($query_vals) - 2);
$q = $query_cols . ') ' . $query_vals . ')';
$this->last_query = $q;
$s = $this->MYSQLI_LINK->prepare($q);
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$count = $s->affected_rows;
$this->last_id = $s->insert_id;
$s->close();
if ($count > 0) {
$this->rows = $count;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
}
public function update($t, $d, $c) {
$a_params = array();
$param_type = '';
$n = count($this->paramTypeArray);
for($i = 0; $i < $n; $i++) {
$param_type .= $this->paramTypeArray[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_bind_params[] = $this->paramBindArray[$i];
}
for($i = 0; $i < $n; $i++) {
$a_params[] = & $a_bind_params[$i];
}
$q = 'update ' . $t . ' set ';
while (list($key, $value) = each($d)) {
$q .= $value . ' = ?, ';
}
//strip comma off end of variable
$q = substr($q, 0, strlen($q) - 2);
$q .= ' where ' . $c;
$this->last_query = $q;
$s = $this->MYSQLI_LINK->prepare($q);
if($s === false) {
trigger_error('Wrong SQL: ' . $q . ' Error: ' . $this->MYSQLI_LINK->errno . ' ' . $this->MYSQLI_LINK->error, E_USER_ERROR);
}
call_user_func_array(array($s, 'bind_param'), $a_params);
$s->execute();
$count = $s->affected_rows;
$s->close();
if ($count > 0) {
$this->rows = $count;
return TRUE;
} else {
$this->last_error = mysqli_error($this->MYSQLI_LINK);
return FALSE;
}
}
} // End Class
Simplified Schema
NOTE: Let me know if you need me to post a more complete schema. This just shows the fields that are linking the joins. All fields are INT(255) unique, id fields are INT(255) AI PRIMARY
SlipMaster links to SlipMain via slipCode, all others link foreign key
to Primary id
SlipMaster (id, slipCode)
SlipMain (id, slipCode, slipContractId, slipClientId, slipVesselId)
ContractMain (id, contractPaymentId)
ClientMain (id)
PaymentMain (id)
VesselMain (id)
* is all the fields in all the tables you are JOINing together. This includes duplicates, such as slipCode, which exists at least twice.
Plan A: Spell out the fields that you really want. This will make it easier to count them and know how many to "bind". And it will make it clear what order to bind them in.
Plan B: Don't use bind_result; simply fetch the result into an array or hash.
Plan C: Do both. (I prefer this.)
#Notorious, I think the answer to your problem is not the sql but to the bind_result() function that you are using.
Explaining furthur, the bind_result() function is used to assign retrieved data from the database to variables. So the number of fields selected (returned from the database) must be equal to the number of binded results.
For instance,
If I selected the firstname and the lastname fields from the database I must use
bind_result($firstname, $lastname);
So as you can see the number of variables in the bind_result() is equal to the number of fields selected.
For your case you are selecting everything from the first db to second to third ..blablabla till the last db. So make sure the number of fields assigned to the the bind_result() function is equal to the number of all the fields returned. That is the sum of the total number of columns in all the databases.
So you got a lot of typing to do but at least its for the best.
Good luck and I hope it helped.

PHP stops execution when calling external function

When the following PHP script executes:
<?php
include "imageManager.php";
include "imageHandling/spritesheet.php";
include "updateWindow.php";
include_once "dbConnection.php";
class deleteSoftware{
private $conn;
private $tableName;
public function __construct($name){
//Database Connection
$this->connectDatabase();
//Delete the Icon from the image pool
$tempFileManagerObject = new fileManager();
$tempFileManagerObject->setSrc("../ICONS/");
$deletedImageName = $tempFileManagerObject->getImageNameFromSoftwareName($name);
$tempFileManagerObject->delete("../ICONS/", $deletedImageName);
$tempFileManagerObject->deleteImageRenaming($deletedImageName);
//Deleting the record from the database
$prio = $tempFileManagerObject->getPriorityFromSoftwareName($name);
$subCategory = $tempFileManagerObject->getSubCategoryFromSoftwareName($name);
$this->tableName = $subCategory;
$this->conn->query("delete from ".$subCategory." where priority=".$prio);
$this->decrementPriorityInTable($prio);
//Delete from updateWindow if exist
$updateObject = new updateWindow();
$updateObject->deleteUpdate($name);
//Making sprite Sheet and moving to home directory
echo "step-0";
$spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../");
echo "step-1";
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->copy("../ICONS/", "../Processing/", $x); }
echo "step-3";
$spriteSheetObject->setImagesFolder("../Processing/");
echo "step-4";
$spriteSheetObject->setOutPutFolder("../");
$spriteSheetObject->processSpriteSheet();
$spriteSheetObject->processSpriteSheetCss($this->getTotalSoftwaresCount());
for ($x = 1; $x <= $spriteSheetObject->getImageCount(); $x++){ $tempFileManagerObject->delete("../Processing/",$x); }
$tempFileManagerObject->setSrc("../Processing/");
$tempFileManagerObject->setDes("../");
$tempFileManagerObject->rename("tempArea", "home");
$tempFileManagerObject->move("../Processing/", "../", "home");
}
public function connectDataBase(){
$temp = new dbConnection();
$this->conn = $temp->connectDb();
}
public function getTheImageNameOfNewlyInsertedIcon($subCategory, $pri){
//First of all calculate the iconName of newly inserted image
//-Get the total number of rows for each subCategory table and add it untill we reach at the subCategory table where software to be inserted (Not add subCategory table rows count)
//- RowCounts + maxPriority in that table + 1
//- If there is already software for
//Calculating the total number of rows upto subCateogryTable excluding the subCategoryTable and then add up
$temp = false;
$rowCount = 0;
$this->tableName;
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
if (!strcmp($row2["category"], $subCategory)){
$this->tableName = $row2["tableName"];
$temp = true;
break;
}
$rowCount = $subCategoryTable->rowCount() + $rowCount;
}
if ($temp){break;}
}
$rowCount = $pri + $rowCount;
return $rowCount;//This will be the name of the image
//Navigate to Tables
//According to priority set the iconName
//Record the iconName please
//Insert the record in table
//Execute the spritesheet
//make css
//finally iterate the whole database and send a string
}
public function decrementPriorityInTable($pri){
$this->conn->query("use windows");
$softwareTable = $this->conn->query("select * from ".$this->tableName." order by priority");
foreach ( $softwareTable as $row ) {
if($row["priority"] >= $pri+1){
$this->conn->query("update ".$this->tableName." set priority=".($row["priority"]-1)." where priority=".$row["priority"]);
}
}
}
public function getTotalSoftwaresCount(){
$softwareCount = 0;
$softwareTable = $this->conn->query("select * from software order by priority");
foreach ( $softwareTable as $row ) {
$categoryTable = $this->conn->query("select * from ".$row["tableName"]." order by priority");
foreach ( $categoryTable as $row2 ) {
$subCategoryTable = $this->conn->query("select * from ".$row2["tableName"]." order by priority");
foreach ($subCategoryTable as $row3){
$softwareCount++;
}
}
}
$softwareCount++;
return $softwareCount;
}
}
?>
The line $spriteSheetObject = new spriteSheet(18, 18, 5, "../ICONS/", "../"); stops executions without any error.
The spriteSheet class comes from this library:
<?php
require("lib/WideImage.php");
//All the images size must first be set to be placed on canvas
//Depends on only 1-Image "canvasArea.jpg"
//image processing folder is by default a "imagesToBeProcessed"
//output folder is empty by default
class spriteSheet{
private $canvasWidth;
private $canvasHeight;
private $eachImageWidth;
private $eachImageHeight;
private $imagesFolder = "";
private $outputFolder = "";
private $imageCount = 0;
private $maxImageInARow;
function __construct($imgW=43,$imgH=43, $maxInRow=5, $src, $des){
$this->imagesFolder = $src;
$this->outputFolder = $des;
$this->imageCounter();
$this->eachImageWidth = $imgW;
$this->eachImageHeight = $imgH;
$this->canvasWidth = $imgW * $maxInRow;
$this->canvasHeight = $imgH * ceil($this->imageCount/$maxInRow);
$this->maxImageInARow = $maxInRow;
}
public function setImagesFolder($src){
$this->imagesFolder = $src;
}
public function setOutPutFolder($des){
$this->outputFolder = $des;
}
public function imageCounter( ){
for ($x=1; true; $x++){
if (!file_exists($this->imagesFolder.$x.".jpg") and !file_exists($this->imagesFolder.$x.".png") and !file_exists($this->imagesFolder.$x.".gif")){
$this->imageCount = $x;
break;
}
}
$this->imageCount--;
}
public function setCanvasSize( ){
$canvas = WideImage::load($this->imagesFolder."canvasArea.jpg")->resize($this->canvasWidth, $this->canvasHeight, "fill");
$canvas->saveToFile($this->imagesFolder."tempArea.jpg");
}
public function resizeAllIcons( ){
$loopEnable = true;
for ($x=1; $loopEnable == true; $x++){
if (file_exists($this->imagesFolder.$x.".jpg")){
$iconImage = WideImage::load($this->imagesFolder.$x.".jpg")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".jpg");
}
else if (file_exists($this->imagesFolder.$x.".png")){
$iconImage = WideImage::load($this->imagesFolder.$x.".png")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".png");
}
else if (file_exists($this->imagesFolder.$x.".gif")){
$iconImage = WideImage::load($this->imagesFolder.$x.".gif")->resize($this->eachImageWidth, $this->eachImageHeight, "fill");
$iconImage->saveToFile($this->imagesFolder.$x.".gif");
}
else{
$loopEnable = false;
}
}
}
public function processSpriteSheet( ){
$this->resizeAllIcons();
$this->setCanvasSize();
$row=0; $col=0; $tempImageCounter = 1;
while ($tempImageCounter<=$this->imageCount){
$icon;
if (file_exists($this->imagesFolder.$tempImageCounter.".jpg")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.jpg');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".png")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.png');
}
else if (file_exists($this->imagesFolder.$tempImageCounter.".gif")){
$icon = WideImage::load($this->imagesFolder.$tempImageCounter.'.gif');
}
else{
break;
}
$canvas = WideImage::load($this->imagesFolder."tempArea.jpg");
$canvas->merge($icon, $row*$this->eachImageWidth, $col*$this->eachImageHeight, 100)->saveToFile($this->imagesFolder."tempArea.jpg");
$tempImageCounter++;
$row++;
if ($row == $this->maxImageInARow){
$row=0;
$col++;
}
}
}
public function processSpriteSheetCss($maxImageCss){
echo "maxImage:".$maxImageCss;
$imgCommon = "img.common{
width: ".$this->eachImageWidth."px;
height: ".$this->eachImageHeight."px;
background-image:url(home.jpg);
}";
$imgS=""; $y=0; $tempImageCounter = 1;
for($x=0; $tempImageCounter<=$maxImageCss; $x++){
$imgS = $imgS."img.s".$tempImageCounter."{background-position:".-1*($x*$this->eachImageWidth)."px ".-1*($y*$this->eachImageHeight)."px;}";
if ($tempImageCounter%$this->maxImageInARow == 0){
$x = -1;
$y++;
}
$tempImageCounter++;
}
echo "SpriteSheetCSS".$imgS;
$handle = fopen( "../css/sprite.css", "w" );
fwrite($handle, $imgS);
}
public function getImageCount(){
echo "total number of images-->".$this->imageCount;
return $this->imageCount;
}
}
?>
My script stops execution at that line without any error.
This file works perfectly on localhost but when I put this online and execute it then this problem happens.

php class _Construct empty

<?
session_start();
/*
echo $_SESSION['SQLIP'];
echo "<br>";
echo $_SESSION['SQLDB'];
echo "<br>";
echo $_SESSION['SQLUSER'];
echo "<br>";
echo $_SESSION['SQLPASS'];
echo "<br>";
*/
class DB_MSSQL {
private $Host;
private $Database;
private $User;
private $Password;
public $Link_ID = 0;
public $Query_ID = 0;
public $Record = array();
public $Row = 0;
public $Errno = 0;
public $Error = "";
public $Halt_On_Error = "yes";
public $Auto_Free = 1;
public $PConnect = 0;
public function _construct(){
$this->Host = $_SESSION['SQLIP'];
$this->Database = $_SESSION['SQLDB'];
$this->User = $_SESSION['SQLUSER'];
$this->Password = $_SESSION['SQLPASS'];
}
function DB_MSSQL($query = "") {
if($query) {
$this->query($query);
}
}
function connect() {
if ( 0 == $this->Link_ID ) {
if(!$this->PConnect) {
$this->Link_ID = mssql_connect($this->Host, $this->User, $this->Password);
} else {
$this->Link_ID = mssql_pconnect($this->Host, $this->User, $this->Password);
}
if (!$this->Link_ID)
$this->connect_failed("connect ($this->Host, $this->User, \$Password) failed");
else
if (!mssql_select_db($this->Database, $this->Link_ID)) {
$this->connect_failed("cannot use database ".$this->Database);
}
}
}
function connect_failed($message) {
$this->Halt_On_Error = "yes";
$this->halt($message);
}
function free_result(){
mssql_free_result($this->Query_ID);
$this->Query_ID = 0;
}
function query($Query_String)
{
/* No empty queries, please, since PHP4 chokes on them. */
if ($Query_String == "")
/* The empty query string is passed on from the constructor,
* when calling the class without a query, e.g. in situations
* like these: '$db = new DB_Sql_Subclass;'
*/
return 0;
if (!$this->Link_ID)
$this->connect();
// printf("<br>Debug: query = %s<br>\n", $Query_String);
$this->Query_ID = mssql_query($Query_String, $this->Link_ID);
$this->Row = 0;
if (!$this->Query_ID) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Invalid SQL: ");
}
return $this->Query_ID;
}
function next_record() {
if ($this->Record = mssql_fetch_row($this->Query_ID)) {
// add to Record[<key>]
$count = mssql_num_fields($this->Query_ID);
for ($i=0; $i<$count; $i++){
$fieldinfo = mssql_fetch_field($this->Query_ID,$i);
$this->Record[strtolower($fieldinfo->name)] = $this->Record[$i];
}
$this->Row += 1;
$stat = 1;
} else {
if ($this->Auto_Free) {
$this->free_result();
}
$stat = 0;
}
return $stat;
}
function seek($pos) {
mssql_data_seek($this->Query_ID,$pos);
$this->Row = $pos;
}
function metadata($table) {
$count = 0;
$id = 0;
$res = array();
$this->connect();
$id = mssql_query("select * from $table", $this->Link_ID);
if (!$id) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Metadata query failed.");
}
$count = mssql_num_fields($id);
for ($i=0; $i<$count; $i++) {
$info = mssql_fetch_field($id, $i);
$res[$i]["table"] = $table;
$res[$i]["name"] = $info->name;
$res[$i]["len"] = $info->max_length;
$res[$i]["flags"] = $info->numeric;
}
$this->free_result();
return $res;
}
function affected_rows() {
// Not a supported function in PHP3/4. Chris Johnson, 16May2001.
// return mssql_affected_rows($this->Query_ID);
$rsRows = mssql_query("Select ##rowcount as rows", $this->Link_ID);
if ($rsRows) {
return mssql_result($rsRows, 0, "rows");
}
}
function num_rows() {
return mssql_num_rows($this->Query_ID);
}
function num_fields() {
return mssql_num_fields($this->Query_ID);
}
function nf() {
return $this->num_rows();
}
function np() {
print $this->num_rows();
}
function f($Field_Name) {
return $this->Record[strtolower($Field_Name)];
}
function p($Field_Name) {
print $this->f($Field_Name);
}
function halt($msg) {
if ("no" == $this->Halt_On_Error)
return;
$this->haltmsg($msg);
if ("report" != $this->Halt_On_Error)
die("Session halted.");
}
function haltmsg($msg) {
printf("<p>Server have a critical error!<br><br><br>We are very sorry for any inconvenience!<br><br>\n", $msg);
printf("<b>MSSQL Error</b>: %s (%s)</p>\n",
$this->Errno,
$this->Error);
}
}
$_php_major_version = substr(phpversion(), 0, 1);
if((4 > $_php_major_version) or !class_exists("DB_Sql"))
{
class DB_Sql extends DB_MSSQL
{
function DB_Sql($query = "")
{
$this->DB_MSSQL($query);
}
}
}
unset($_php_major_version);
?>
I have a question, why on DB_MSSQL my $Host,$Datebase,$User,$Password are empty?
If i test $_SESSIONS Between DB_MSSQL are OK.
Class don't have errors but this variables are empty... and i don't know why..
Can anybody help me?
Thank you verry much!
You have missed one underscore, you should have write :
public function __construct()
It should work like this.

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.

OOP in PHP - object array iteration

I am trying to iterate through array of objects in PHP, but I can't figure it out. This is my code:
require_once("databaseConnect.php");
require_once("class/Ticket.php");
function showAll(){
$sql = "SELECT * FROM Ticket WHERE Status='1'";
$p = mysql_query($sql);
while ($row = mysql_fetch_object($p)){
$t = new Ticket($row->IDTicket, $row->IDUser, $row->TotalOdd, $row->PlacedBet, $row->PossibleWin, $row->Status, $row->Won, $row->Time);
$nizTiketa[] = $t;
}
return $nizTiketa;
}
$niz = showAll();
for ($i; $i<count($niz); $i++){
echo $niz[$i]->getIDTicket()."<br/>";
}
and this is class Ticket:
class Ticket {
private $IDTicket;
private $IDUser;
private $TotalOdd;
private $PlacedBet;
private $PossibleWin;
private $Status;
private $Won;
private $Time;
function Ticket($idTicket, $idUser, $totalOdd, $placedBet, $possibleWin, $status, $won, $time) {
$this->IDTicket = $idTicket;
$this->IDUser = $idUser;
$this->TotalOdd = $totalOdd;
$this->PlacedBet = $placedBet;
$this->PossibleWin = $possibleWin;
$this->Status = $status;
$this->Won = $won;
$this->Time = $time;
}
function getIDTicket(){
return $this->IDTicket;
}
function setIDTicket($idTicket){
$this->IDTicket = $idTicket;
}
.
.
.
I got error Call to a member function getIDTicket() on a non-object
How should it be done?
Couple of things I'd do here for sanity...
As mentioned by Joe, initialise your array before adding elements, eg
function showAll() {
$nizTiketa = array();
// ...
Either initialise your iteration counter $i to zero
for ($i = 0, $count = count($niz); $i < $count; $i++)
or more simply, use foreach
foreach ($niz as $ticket) {
echo $ticket->getIDTicket(), "<br/>";
}

Categories