1

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?

3
  • 3
    Just for sanity, add in $nizTiketa = array(); at the top of function showAll() - always initialise your array before adding something into it :) Commented Feb 9, 2012 at 0:13
  • Are you sure that you must initialize array in php? Commented Feb 9, 2012 at 0:15
  • 1
    The thing is that the variable $nizTiketa will not exist if no rows matched the query. That's strictly speaking an error you'll want to avoid by initializing the variable. Commented Feb 9, 2012 at 0:19

1 Answer 1

1

Couple of things I'd do here for sanity...

  1. As mentioned by Joe, initialise your array before adding elements, eg

    function showAll() {
        $nizTiketa = array();
        // ...
    
  2. 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/>";
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.