samedi 2 janvier 2016

Access PHP PDO SQL Query Result From Another Class File

Am trying to access the result of SQL query in SQLite using PHP from another class. I have read similar questions here and here. But still have not found a solution to my problem. This is what I have done.

Connect.php

<?php

$dsn = 'sqlite:leDB.db';
$db = new PDO($dsn);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

DBMan.php

<?php

Class DBMan{

private $dsn = 'sqlite:leDB.db';
private $db;

    public function __construct(){

        $this->db = new PDO($this->dsn);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

public function showData(){


        try{

            $sql = 'SELECT * FROM fruits';
            $stmt= $this->db->query(sql);

            if(!$stmt){
                throw new PDOException('Error displaying fruits');
            }
            $data = $stmt->fetchAll(FETCH_ASSOC);
            return $data;
        }
        catch (PDOException $e){
            echo 'Error\n';
            echo '$e->getMessage()';

        }
  }
}
?>

MaView.php

    <?php
    class MaView{

        function __autoload($class){
            include_once($class.".php");

        }

        $db=new DBMan();

       <?php
       $val = $dat->showData();
       foreach ($val as $row) {?>
         <H1><? echo row['fruit_name']?></H1>
       <? }?>

    }
?>

Can someone please show me where I have blundered?

Aucun commentaire:

Enregistrer un commentaire