栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在课堂上使用PDO

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在课堂上使用PDO

您可以在实现单例模式的类中实例化与数据库的连接。连接将完成一次,所有其他对象/脚本都可以轻松访问该类。

在下面的示例中,我使用称为“ Core”的类;

class Core{    public $dbh; // handle of the db connexion    private static $instance;    private function __construct()    {        // building data source name from config        $dsn = 'pgsql:host=' . Config::read('db.host') .    ';dbname='    . Config::read('db.basename') .    ';port='      . Config::read('db.port') .    ';connect_timeout=15';        // getting DB user from config  $user = Config::read('db.user');        // getting DB password from config  $password = Config::read('db.password');        $this->dbh = new PDO($dsn, $user, $password);    }    public static function getInstance()    {        if (!isset(self::$instance))        { $object = __CLASS__; self::$instance = new $object;        }        return self::$instance;    }    // others global functions}

该类从名为“ Config”的静态类中获取参数,您可以在其中存储配置:

<?phpclass Config{    static $confArray;    public static function read($name)    {        return self::$confArray[$name];    }    public static function write($name, $value)    {        self::$confArray[$name] = $value;    }}// dbConfig::write('db.host', '127.0.0.1');Config::write('db.port', '5432');Config::write('db.basename', 'mydb');Config::write('db.user', 'myuser');Config::write('db.password', 'mypassword');

在所有脚本/对象中,您只需要获取Core的实例,然后查询数据库

$sql = "select login, email from users where id = :id";try {    $core = Core::getInstance();    $stmt = $core->dbh->prepare($sql);    $stmt->bindParam(':id', $this->id, PDO::PARAM_INT);    if ($stmt->execute()) {        $o = $stmt->fetch(PDO::FETCH_OBJ);        // blablabla....

如果您需要有关单例的更多信息,请查看PHP文档http://php.net/manual/en/language.oop5.patterns.php



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402738.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号