Help to populate an array with objects using a while

1

I want to read rows from a SQL and use them to create objects and finally put these objects in an array. But in the end my methods (of the class Object) do not print the name of the object. The code to read only one line works, so the problem is certainly in the array .

<?php
    require_once 'Object.php';
    require("connect.inc");
    connect_db() or die ("Error.");
    $result=mysql_query("SELECT * FROM object") or die ("Error");

    $count = 0;
    $c[] = array();
    while ($line=mysql_fetch_array($result) && $count < 6) {
        $count ++;
        $c[$count] = new Object($line);
    }

    print ($c[1]->getName()); // Example

?>
    
asked by anonymous 27.11.2016 / 20:54

1 answer

5

If the intention is to store the rows in the form of an object in the array and display later, it could be done like this:

<?php
    require_once 'Object.php';
    require("connect.inc");
    connect_db() or die ("Error.");
    $result=mysql_query("SELECT * FROM object") or die ("Error");


    $c[] = array();

    while ($line=mysql_fetch_object($result) ) {
        $c[] = $line;
    }


    foreach($c as $line){
        echo $line->coluna1;//altere pelo nome das colunas da sua tabela
    }

?>

I strongly suggest that you remove the mysql functions, because Your development has been discontinued . Replace mysqli or PDO .

    
27.11.2016 / 21:26