使用函数pdo从db检索数据

时间:2013-05-17 11:44:16

标签: php function pdo

这是实现函数之前的代码,

try {
    $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
    $stmt = $conn->prepare('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5');
    $stmt->execute(array(':published' => 'published'));
    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $contents = $result['content'];
    $title = $result['title']; 
.... 

这很好用。然后我将db连接命令移动到单独的php文件(functions.php)。并创建了这个功能,

function run_db($sqlcom,$exe){
    $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare($sqlcom);
    $stmt->execute($exe);
    $data_db = $stmt->fetch(PDO::FETCH_ASSOC) ;
    return $data_db;
}

然后我改变了第一个提到这样的代码,

try {
    $data_db=run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' => 'published'));   
    while ($result = $data_db) {
    $contents = $result['content'];
    $title = $result['title']; 

然后我得到的是一个无限重复的帖子。有谁能告诉我如何纠正这个问题?

4 个答案:

答案 0 :(得分:3)

将功能更改为:

function run_db($sqlcom,$exe){
    $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare($sqlcom);
    $stmt->execute($exe);
    return $stmt;
}

并调用该函数:

try {
    $stmt = run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' => 'published'));   
    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $contents = $result['content'];
        $title = $result['title'];

编辑:更好的解决方案是 jeroen 建议 - 一次性返回所有提取的对象

function run_db($sqlcom,$exe){
    $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare($sqlcom);
    $stmt->execute($exe);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

然后这样说:

try {
    $data = run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' => 'published'));   
    foreach($data as $result) {
        $contents = $result['content'];
        $title = $result['title'];

编辑2:无论如何 - 将这样的逻辑包装到一个函数中并不是一个好主意。现在,您仅限于执行SELECT个查询,并且生成的数组始终只包含记录的关联数组。如果您希望(出于任何原因)检索对象的数组,甚至只有一个值,该怎么办?如果您要执行INSERTUPDATEDELETE查询该怎么办?

如果你肯定想要这样,那么我想创建一个具有这样功能的类:

class MyPDO {
    private $connection;

    static $instance;

    function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');
        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    static function getInstance() {
        return self::$instance ?  : self::$instance = new MyPDO;
    }

    // retrieves array of associative arrays
    function getAssoc($sqlcom, $exe) {
        $stmt = $this->connection->prepare($sqlcom);
        $stmt->execute($exe);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // retrieves array of objects
    function getObj($sqlcom, $exe) {
        $stmt = $conn->prepare($sqlcom);
        $stmt->execute($exe);

        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    // retireves one single value, like for SELECT 1 FROM table WHERE column = true
    function getOne($sqlcom, $exe) {
        $stmt = $conn->prepare($sqlcom);
        $stmt->execute($exe);

        return $stmt->fetchColumn();
    }

    // just executes the query, for INSERT, UPDATE, DELETE, CREATE ...
    function exec($sqlcom, $exe){
        $stmt = $conn->prepare($sqlcom);

        return $stmt->execute($exe);
    }
}

然后你可以这样称呼它:

try {
    $pdo = MyPDO::getInstance();
    foreach($pdo->getAssoc('MySQL QUERY'), array($param, $param)) as $result) {
        print_r($result);
    }
} catch(\Exception $e) {
    // ...
}

答案 1 :(得分:2)

只需返回声明:

function run_db($sqlcom,$exe){
    static $conn;
    if ($conn == NULL)
    {
        $conn = new PDO('mysql:host=localhost;dbname=dbname', 'usr', 'pass');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    $stmt = $conn->prepare($sqlcom);
    $stmt->execute($exe);
    return $stmt;
}


try {
    $stmt=run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' => 'published'));   
    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $contents = $result['content'];
    $title = $result['title']; 

您还可以在连接上设置默认的fecth模式。

答案 2 :(得分:0)

从函数返回$stmt的正确答案的替代方法是函数中的fetch all rows,并在主代码中使用foreach

在功能中:

...
$data_db = $stmt->fetchAll(PDO::FETCH_ASSOC) ;
return $data_db;

功能之外:

$data_db=run_db('SELECT * FROM posts WHERE status= :published ORDER BY id DESC LIMIT 5',array(':published' => 'published'));   
foreach ($data_db as $result) {
  $contents = $result['content'];
  $title = $result['title']; 
  ...

答案 3 :(得分:0)

您的代码存在两个基本问题。

  1. 每次运行查询时都会连接。
  2. 它只返回一种格式的数据,而PDO可以返回数十种不同格式的结果。
  3. 接受的答案是错误的,因为它只是试图重新发明PDO功能,但是很脏的方式,有很多重复的代码,但仍然无法像使用香草PDO一样好。

    正如在xdazz的回答中所说,你必须返回声明。然后使用PDO的本机提取模式,使用方法链接以所需格式获得结果。

    此外,您不应在代码中添加try

相关问题