1

I need pass array from m.php back to index.php and loop to print each row, but I can't find way how to do it? any suggestion will be appreciated.

below code I use return $rows in m.php but index.php can't get it..

index.php

<?php
require 'm.php';

$select_news = new select_news();
$select_news->select_3();
print_r($rows);
foreach ($rows as $row){
?>
<div><?=$row['id']?></div>
...
<?php
}
?>

m.php

class select_news{
    public function select_3(){
        global $db;
        $sth = $db->prepare('SELECT * FROM news ORDER BY id DESC LIMIT 3');
        $sth->execute();
        $rows = $sth->fetchAll();
            return $rows;
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
  • just a thought, but it looks like you're not assigning the result to a variable... – ermagana Oct 13 '13 at 03:50
  • 1
    Just so you know why this didn't work, it's variable scope. In your select_3 function you use $rows, but that variable isn't visible to anything other than that specific function - it isn't a global variable. So in your index.php $rows is undefined, because it isn't the same variable as $rows in your class function! Thus why you need to assign the return value to a variable in index.php, as the answers indicate. – BrianH Oct 13 '13 at 03:54
  • Please stop using global variables for connection. Instead you should inject it as a dependency. [This](http://stackoverflow.com/a/11369679/727208) post should provide you with a viable alternative and some materials for further study. – tereško Oct 13 '13 at 11:53

2 Answers2

1

Just assign the value of that function call to a variable…

$select_news = new select_news();
$rows = $select_news->select_3();
print_r($rows);
foreach ($rows as $row){
?>
<div><?=$row['id']?></div>
...
<?php
}
?>
kojiro
  • 74,557
  • 19
  • 143
  • 201
0

To convert it to an array (if I read the question correctly), you can put this right above your foreach statement:

$rows = unserialize(serialize(json_decode(json_encode((array) $rows), 1)));
jerdiggity
  • 3,655
  • 1
  • 29
  • 41