PDO查询类

时间:2013-08-23 16:45:19

标签: php pdo

我正在修补一个“应该'允许我轻松执行fetchall查询并在foreach语句中显示结果。我认为一切都正常,因为我没有错误。至于foreach - 这一定是问题吗?我如何预测从$connect->query()获得的结果?我在我的函数中使用任何数据库OOP框架都是新手,所以我可能完全走错了路线。

 <?

error_reporting(1);

class dbconnect {

private $host;
private $database;
private $username;
private $password;

private $pdo;
private $error;

    public function __construct() {

        $this->host     = "localhost";              // Host
        $this->database = "images";                 // Database Name
        $this->username = "*";              // Username
        $this->password = "*";  // Password
        $options  = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
        );

        try {
            $this->pdo = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password, $options);
        }
        catch(PDOException $e) {
            $this->error = $e->getMessage();
        }

    }

    public function query($query) {

        try {
            $stmt = $this->pdo->prepare($query);
            $stmt->execute(); 
        } catch(PDOException $ex) { 
            die("Failed to run query: " . $ex->getMessage()); 
        } 

        $rows = $stmt->fetchAll();
        return $rows;

    }

}

$connect = new dbconnect;
$rows = $connect->query("select * from photos");
foreach($rows as $row):
    print $row['id'];
endforeach;



?>

4 个答案:

答案 0 :(得分:2)

非常确定您实际上并未执行查询:

        $this->stmt = $this->pdo->prepare($query);
        $stmt->execute(); 

我相信(我可能错了,我自己对PDO很陌生,而且我还没有建立一个类),你需要说$ this-&gt; stmt-&gt; execute(); < / p>

答案 1 :(得分:2)

您在$rows内声明的query变量无法在外部访问,它是该函数的本地变量。最有可能的是,您只想将return这些结果发送给来电者:

$rows = $stmt->fetchAll();
return $rows; // return value from function...

并让调用者捕获返回值在其自己的变量中:

$rows = $connect->query("select * from images"); // ... is received by caller
foreach($rows as $row):

同时查看dougjore的答案,您在$this->stmt方法中混合了$stmtquery

答案 2 :(得分:1)

你可以做到

// PDO :: FETCH_ASSOC:返回按结果集中返回的列名索引的数组

$this->stmt = $this->pdo->prepare($query);
$this->stmt->execute();

while ($result = $this->stmt->fetch(PDO::FETCH_ASSOC))
{

  //do something with the result
}

在这里查看有关获取PDO查询结果的更多选项: http://php.net/manual/en/pdostatement.fetch.php

答案 3 :(得分:0)

$connect = new dbconnect;
$sql="select * from photos";
$stmt=$connect->pdo->prepare($sql); 
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
   echo $key . "-" . $value . "<br/>";
}