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;
    }
}
3
  • just a thought, but it looks like you're not assigning the result to a variable... Commented Oct 13, 2013 at 3: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. Commented Oct 13, 2013 at 3:54
  • Please stop using global variables for connection. Instead you should inject it as a dependency. This post should provide you with a viable alternative and some materials for further study. Commented Oct 13, 2013 at 11:53

2 Answers 2

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
}
?>
Sign up to request clarification or add additional context in comments.

Comments

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)));

Comments

Your Answer

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