2016-01-03 35 views
-2

我试图从另一个类使用PHP访问SQLite中SQL查询的结果。我读过类似的问题herehere。但仍然没有找到解决我的问题。这就是我所做的。从另一个类文件访问PHP PDO SQL查询结果

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

        if(!$stmt){ 
         throw new PDOException('Error displaying fruits'); 
        } 

        $data = $stmt->fetchAll(PDO::FETCH_ASSOC); //UPDATED 
        return $data; 
       } 
       catch (PDOException $e){ 
        echo 'Error\n'; 
        echo $e->getMessage(); //UPDATED  
       } 
      } 
    } 
?> 

MaView.php

<?php 
class MaView 
    { 
     include_once("DBMan.php"); //UPDATED 
     $db = new DBMan(); 

     $val = $db->showData(); 
     foreach ($val as $row) { 
      echo "<H1>" . $row['fruit_name'] . "</H1>"; //UPDATED 
     }        
    } 
?> 

是否有人可以告诉我在哪里我都失蹄?

+1

您还没有在MaView类中包装脚本(在__autolad()方法之后)。 – Rasclatt

+0

谢谢。我删除了自动加载功能。表格仍然没有显示。 – DBoonz

+0

你可以用你现在拥有的东西来更新你的问题吗? – Rasclatt

回答

0

好了,我终于想通了。谢谢你的回复以及你的耐心。做新手并不容易,学习很多。 我在一个单独的类中分离连接设置,以进一步模块化。

//Keys.php returns a database connection 

<?php  
    class Keys 
    { 
     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); 
     } 

     function getDB(){ 
      return $this->db; 
     } 
    } 
?> 

DBMan类。执行所有数据库操作。我犯的错误是使用fetchAll()来显示我所有的结果。 FetchAll()返回结果数组,但循环显示每个结果并不是直截了当的。 为了弥补这一点,我使用了fetch(),然后遍历所有结果并将它们存储在一个数组中。这是代码。

//Class DBMan handles database queries and returns results in an array 

    <?php 
    Class DBMan 
     { 

      private $con; 
      public function __construct(Keys $key) 
       { 
        $this->$con = $key; 
       } 
      public function showData() 
       { 
        try{ 
         $sql = 'SELECT * FROM fruits'; 
         $stmt=$this->con->getDB()->query($sql); 

         if(!$stmt){ 
          throw new PDOException('Error displaying fruits'); 
         } 


         while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
          $data [] = $row; 
         } 

         return $data; 
        } 
        catch (PDOException $e){ 
         echo 'Error\n'; 
         echo $e->getMessage();  
        } 
       } 
     } 
    ?> 

我使用方法fetchAssoc()来获取关联数组并将结果存储在数组中。这给了我一个多维数组。为了访问我的值,for循环必须循环遍历每一行并挑选出键。这就是我所做的。

//MaView.php displays information from the database 

    <?php 
    class MaView 
     { 
    include_once('Keys.php'); 
    include_once ('DBman.php'); 
    $key = new Keys(); 
    $db = new Datman($key);  

    $val = $db->showData(); 
      foreach ($val as $row => $key) {?> 

       <h1><?php echo $key['fruit_name']?></h1> 

      <?php } ?> 

     } 
    ?> 

我已将PHP代码与html混合。起初读起来有点困难,但它是正确的。再次感谢您的全力帮助。

1

有几个问题与您的PHP代码。我更新了你的代码如下 DbMan.php

public function showData() 
{ 
    try { 
     $sql = 'SELECT * FROM fruits'; 
     $stmt= $this->db->query($sql); // updated 

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

MaView.php

include_once("DbMan.php"); 

$db = new DbMan(); 
$val = $db->showData(); 
foreach ($val as $row) { 
    echo "<H1>" . $row['fruit_name'] . "</H1>"; 
} 
+0

谢谢。我已经做了必要的改变。但是,它仍然没有显示。 – DBoonz

+0

您的MaView.php类错误。请用以下代码更新该文件的内容:'include_once(“DbMan.php”); $ db = new DbMan(); $ val = $ db-> showData(); ($ val as $ row){ echo“

”。 $ row ['fruit_name']。 “

”; }' – mhr

+0

谢谢。我这样做了...... – DBoonz

0

我认为你需要这些元素分离出来,并组织他们到单个文件各自做各自的任务或任务组的类似的任务:

/classes/class.DatabaseConfig.php

<?php 
// This is your database class, just deals with connection 
// and automated array returns 
class DatabaseConfig 
    { 
     private static $singleton; 
     private static $con; 
     private $query; 

     public function __construct() 
      { 
       if(empty(self::$singleton)) 
        self::$singleton = $this; 

       return self::$singleton; 
      } 

     public function connect($db = 'sqlite:leDB.db') 
      { 
       if(!empty(self::$con)) 
        return self::$con; 

       try { 
        self::$con = new PDO($db); 
        self::$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
       } 
       catch (PDOException $e) { 
        die("Connection failed"); 
       } 

       return self::$con; 
      } 

     public function query($sql,$bind = false) 
      { 
       $con = $this->connect(); 

       if(!empty($bind)) { 
        $this->query = $con->prepare($sql); 
        $this->query->execute($bind);     
       } 
       else { 
        $this->query = $con->query($sql); 
       } 

       return $this; 
      } 

     public function getResults() 
      { 
       if(empty($this->query)) 
        return 0; 

       while($row = $this->query->fetch(PDO::FETCH_ASSOC)) { 
        $result[] = $row; 
       } 

       return (!empty($result))? $result : 0; 
      } 
    } 

/classes/class.DBMan.php

<?php 
// This is just your DBMan Class, but it's not doing much 
// except returning an array for this table 
class DBMan 
    { 
     public static function showData() 
      { 
       return qEngine()->query('SELECT * FROM `fruits`')->getResults(); 
      } 
    } 

/classes/class.MaView.php

​​

/functions/function.qEngine.php

<?php 
// This simply returns the database connection 
function qEngine() 
    { 
     return new DatabaseConfig(); 
    } 

/autoloader.php

<?php 
// This autoloads classes based on a specific directory structure 
spl_autoload_register(function($class) { 
    if(!class_exists($class)) { 
     $incFile = ROOT_DIR.'/classes/class.'.$class.'.php'; 
     if(is_file($incFile)) 
      include_once($incFile); 
     } 
    }); 

/config.php

<?php 
// Make some defines 
define('ROOT_DIR',__DIR__); 
// Include the class autoloader 
include_once(ROOT_DIR.'/autoloader.php'); 
// Include the query function 
include_once(ROOT_DIR.'/functions/function.qEngine.php'); 

的index.php

<?php 
// Add the config to every page 
require(__DIR__.'/config.php'); 
// You don't need to include anything for classes 
// the spl_autoload_register() does it automatically 
// provided your directories are set as indicated 
echo MaView::displayFruits();