Home > front end >  Php: Unable to display class array properties
Php: Unable to display class array properties

Time:06-26

I'm passing values from the MS SQL database to a class public property of a multi-dimensional array.

class SalesInvoice {

  public $invLineItems=array();

  public function  fnSalesInvoice(){
      while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) //WHILE-801   //SQLSRV_FETCH_ASSOC to use column name
      {
        // code updated for reference
        $this->invLineItems[]= array(
              "lineId"=>$row["idInvoiceLines"], "module"=> $row["iModule"] ... ); // more fields added
      }
      
      print_r($this->invLineItems; // array elements printed with values

  }
}

And the print_r() line display the array elements with correct values.

enter image description here

However, when traversing array elements in the client the array shows empty.

require_once('salesinvoice.php');
$saleinvoice = new SalesInvoice();

$salesinvoice->fnSalesInvoice($_GET["tx"]);

// array printed without values
print_r($salesinvoice->invLineItems) ;


// array printed without values
foreach($salesinvoice->invLineItems as $arr =>$val){
    echo "<br>". $val["lineId"] . $val["module"] ;
}

CodePudding user response:

change your class to bellow

class SalesInvoice
{
    public $invLineItems = [];

    public function fnSalesInvoice($stmt)
    {
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) //WHILE-801   //SQLSRV_FETCH_ASSOC to use column name
        {
            $this->invLineItems[] = [
                "lineId" => $row["idInvoiceLines"], "module" => $row["iModule"]]; // more fields added
        }
    }


}

after this you problem solved

  • Related