正确使用不使用全局的PDO程序

时间:2014-09-04 21:52:01

标签: php mysql pdo

我正在玩PDO并且目前有以下代码,但我得到Call to a member function prepare() on a non-object并且我不想使用全局。

我是否使用课程或将其作为变量传递?

CONFIG.PHP

function connection()
{
    try
    {
        $host   = 'localhost';
        $dbuser = '';
        $dbpass = '';
        $dbname = '';
        $dbConnection = new PDO("mysql:host=" . $host . ";dbname=" . $dbname.";", $dbuser, $dbpass);
        return $dbConnection;
    } catch (PDOException $error)
    {
        echo $error->getMessage();
        return FALSE;
    }
}

的functions.php

<?php

include('config.php');

$db =  connection();

function listCars()
{
    $query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");

    $result = $query->fetchAll();

    return $result;
}

?>

的index.php

<?php  
    include('assets/misc/functions.php');

    var_dump(listcars());                

?>

1 个答案:

答案 0 :(得分:2)

你必须将db变量加载到你的函数中,在Functions.php中,看看这个:

<强>的functions.php     

    include('config.php');

    $db =  connection();

    function listCars($db){

        $query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");

        $result = $query->fetchAll();

        return $result;
    }

?>

<强>的index.php

<?php  
    include('assets/misc/functions.php');

    var_dump(listcars($db));                

?>

但是,如果您正在寻找更多OOP方法,请尝试以下方法:

<?php 

    class Cars {
        protected $db;

        public function __construct(PDO $db){
            $this->db = $db;
        }

        public function listCars(){
            $query = $this->db->prepare("... query ...")->execute();
            return $query->fetchAll();
        }
    }

    include('config.php');

    $cars = new Cars(connection());

    try {
        var_dump($cars->listCars());
    } catch (PDOException $e) {
        echo $e;
    }
?>