开发者

what is wrong with this PDO code?

开发者 https://www.devze.com 2023-02-15 10:36 出处:网络
I have created a file name database.php and here is it\'s content <?php #Start Session session_start();

I have created a file name database.php and here is it's content

<?php
#Start Session
session_start();
#Start Output Buffering
ob_start();
#Set Default TimeZone
date_default_timezone_set('Asia/Kolkata');

#Define Connection Constant
define('HOST','localhost');
define('USERNAME','user');
define('PASSWORD','pass');
define('DATABASE','database');
//Define Configuration Constant
define('DATE', date("d-F-Y/H:ia"));

#Connect to the database
try
{
    #Define Connection String Using PDO.
    $DBH = new PDO('mysql:host='.HOST.';dbname='.DATABASE,USERNAME,PASSWORD);

    #Set Error Mode to ERRMODE_EXCEPTION.
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo $e->getMessage();
    //Log Errors into a file
    file_put_contents("resources/logs/Connection-log.txt", DATE.PHP_EOL.$e->getMessage().PHP_EOL.PHP_EOL, FILE_APPEND);
}
?>

and now i have defined a PHP's class and i have declared a method where i want to fetch some values based on the connection above. i have included the database.php file.

here is my code.

include('../../config/database.php');
class Property
{
    public function getAllCountries()
    {
        #Query Using Prepared Statement
        $STH = $DBH->query('SELECT * FROM countries');

        #Set the Fetch Mode
        $STH->setFetchMode(PDO::FETCH_ASSOC);

        $countries = array();
        while($row = $STH->fetch())
        {
            $countries[] = $row['name'];
            return $countries;
        }
    }
}
$property = new Property;
echo $property->getAllCountries();

when i initialize the class it doesn't have any problem but when i try to call $property->getAllCountries(); method it gives me the following error.

Notice: Undefined variable: DBH in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/class.property.php on line 8

Fatal error: Call to a member function query() on a non-object in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/class.property.php on line 8

what is wrong with m开发者_JAVA百科y code?


The problem is that $DBH is not in scope at the time of the call $DBH->query(). $DBH is in the global scope, while the call is within a function's scope (getAllCountries). Unlike some other languages, global variables are not accessible within functions unless you specifically declare them.

The one-line workaround for this is to use the global value of $DBH within the function:

public function getAllCountries()
{
    global $DBH;

    #Query Using Prepared Statement
    $STH = $DBH->query('SELECT * FROM countries');

However, this is probably a bad idea, because you have now locked yourself in to a particular way of handling database connections. It would be better to pass the database object as a parameter to the constructor, store it in an object variable, and retrieve it when you need to use it.

class Property
{
    protected $dbh;

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

    public function getAllCountries() {
        $STH = $this->dbh->query('SELECT * FROM countries');

        [snip]
    }    
}

You would then need to initialise your class with the DB object passed as a parameter:

$property = new Property($DBH);
echo $property->getAllCountries();


try to pass the handle to the dbh in the constructor of the class and reserve upper case variable names only for globals and constants... Avoid using global variables in your class...

Second Issue: Return countries outside of the loop!

class Property
{

    protected $dbh;

    public function __construct($dbhandle) {
      $this->dbh = $dbhandle;
    }


    public function getAllCountries()
    {
        #Query Using Prepared Statement
        $sth = $this->dbh->query('SELECT * FROM countries');

        #Set the Fetch Mode
        $sth->setFetchMode(PDO::FETCH_ASSOC);

        $countries = array();
        while($row = $sth->fetch())
        {
            $countries[] = $row['name'];
        }

        // !! return goes here!
        return $countries;
    }
}

$property = new Property($DBH);
echo $property->getAllCountries();
0

精彩评论

暂无评论...
验证码 换一张
取 消