如何在不同文件中使用PDO连接对象 [英] how to use PDO connection object in different files

查看:80
本文介绍了如何在不同文件中使用PDO连接对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是使用MySQL进行PDO的新手,这是我的两个文件 1)index.php

Hello i am new to PDO with MYSQL, here are my two files 1) index.php

require_once 'prd.php';
try{
    $db = new PDO ('mysql:host=xxxx;dbname=xxx;charset=utf8', 'xxx', 'xxxx');
    echo 'connectd';
}catch(PDOException $conError){
    echo 'failed to connect DB' . $conError->getMessage ();
}
$conn = new prdinfo();
$conn->con($db);

2)product.php

class prdinfo{function con($db){
    try{
        foreach($db->query("select * from products where vendor_id = 2" ) as $row){
            $prod_id = $row ['product_id'];
            echo '<br/>' . $prod_id;
        }
    }catch(PDOException $ex){
        echo 'an error occured' . $ex->getMessage();
    }
}
}

我的问题是在这里我可以将连接对象传递给每个文件,但是我有太多文件要使用数据库查询,因此我需要将$ bd传递给所有文件.这给代码增加了负担.因此,有什么方法可以将数据库与PDO连接. 谢谢

my problem is here i can pass the connection object to every file, but i have so many files to use database queries, so i need to pass the $bd to all the files. this is getting burden on the code. so is there any way to connect the database with PDO. Thanks

推荐答案

1)pdo.php,仅三行:

1) pdo.php, three lines only:

<?
$pdo = new PDO ('mysql:host=xxxx;dbname=xxx;charset=utf8', 'xxx', 'xxxx');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

2)product.php

2) product.php

<?php

class prdinfo{

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

    function getVendor($vendor)
    {
        $sql = "select * from products where vendor_id = ?";
        $stm = $this->db->prepare($sql);
        $stm->execute(array($vendor));
        return $stm->fetchAll();
    }
}

3)index.php

3) index.php

<?php
require 'pdo.php';
require 'product.php';

$info   = new prdinfo($pdo);
$vendor = $info->getVendor(2);
foreach ($vendor as $row)
{
    echo $row['product_id'];
}

这篇关于如何在不同文件中使用PDO连接对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆