从另一个类文件访问PHP PDO SQL查询结果

时间:2016-01-03 02:04:12

标签: php sqlite oop pdo

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

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
        }                             
    }
?>

有人可以告诉我我在哪里犯了错误吗?

3 个答案:

答案 0 :(得分: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>";
}

答案 1 :(得分: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

<?php
// This is just the view class. It outputs to buffer so it
// can be echoed to the page
class MaView
    {
        public  static  function displayFruits()
            {
                $val    =   DBMan::showData();
                if(!is_array($val))
                    return false;

                ob_start();
                foreach($val as $row)
                    echo "<H1>".$row['fruit_name']."</H1>";

                $data   =   ob_get_contents();
                ob_end_clean();

                return $data;
            }
    }

<强> /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();

答案 2 :(得分: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混合在一起。起初它有点难读,但它是正确的。再次感谢您的帮助。