0

I can't get my data from database , I keep getting the same error

Notice: Undefined variable: articles in :\xampp\htdocs\SalesManagementProject\Views\articles.php on line 25
Warning: Invalid argument supplied for foreach() in :\xampp\htdocs\SalesManagementProject\Views\articles.php on line 25

my loop

 <?php
 foreach($articles as $art)
 {
  echo '<tr>
         <td>'.$art['Id'].'</td>
         <td>'.$art['ref'].'</td>
         <td>'.$art['desig'].'</td>
        </tr>';
 }
 ?>

Model

 <?php
class ArticlesModel
{
    public function getArticles()
    {
        $pdo=new PDO_connect();
        $q= $pdo->PDO()->query('SELECT * FROM articles');
        return $q->fetchAll();
    }
}
?>

Controller

<?php
class ArticlesControllers
{
    public function loadArticles()
    {
        include (dirname(__FILE__).'/../Models/ArticlesModel.php');
        $art_table = new ArticlesModel();
        $articles = $art_table->getArticles();
        include(dirname(__FILE__).'/../Views/articles.php');
    }
}
?>

index

<?php
   session_start();
  include ('PDO_connect.php');
   $p='home';

  if (isset($_GET['p']))
  {
       $p=$_GET['p'];
   }
   include('Controllers/ArticlesControllers.php');
$arts=new ArticlesControllers();
$arts->loadArticles();
?>

So what i must do?

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

-1

Simple, in your controller section after the public function loadArticles() { add

global $articles;

Because $articles is assigned inside of a function, you need to global it to read it in another area.
BTW you should define $articles as an array in index.php to make it properly defined

 $articles = array();

BTW passing a named variable in / out of a class is not very proper programming, but I wanted you to have a quick solution.

A better solution is to have the public function return ($articles) and in your index.php $articles = $arts->loadArticles();

Forbs
  • 1,256
  • 1
  • 7
  • 9
  • Thank you I did that but its still now work ok there is no Warning now but does not bring anything from database :( – M. Hasimi Aug 29 '16 at 12:20
  • Well that's a different matter you will have to use `print_r` in various places – Forbs Aug 29 '16 at 14:09