PDO :: FETCH_CLASS和PDO :: FETCH_INTO之间有什么区别

时间:2015-06-30 09:27:55

标签: php

我发现PDO :: FETCH_CLASS和PDO :: FETCH_INTO之间没有任何区别。你能告诉我一个关于它们之间区别的例子吗?

2 个答案:

答案 0 :(得分:0)

请参阅此PHP PDO fetching into objects

以下示例

<?php

$sql_server = "localhost";
$sql_db = "test";
$sql_user = "root";
$sql_pass = "";

$pdo = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);

$sql = 'SELECT firstName, lastName FROM users';

$stmtA = $pdo->query($sql);
$stmtA->setFetchMode(PDO::FETCH_CLASS, 'Person');

$objA = $stmtA->fetch();
var_dump($objA);

//first create the object we will fetch into
$objC = new Person;
$objC->firstName = "firstName";
$objC->lastName = "lastName";

$stmtC = $pdo->query($sql);
$stmtC->setFetchMode(PDO::FETCH_INTO, $objC);

$objC = $stmtC->fetch(); // here objC will be updated
var_dump($objC);


class Person{
    public $firstName;
    public $lastName;
}

答案 1 :(得分:0)

  

PDO :: FETCH_CLASS:返回指定类的实例,将每行的列映射到类中的命名属性。

<?php
class fruit 
{
    public $name;
    public $colour;
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);
?>

以上示例将输出类似于:

的内容
array(3) {
  [0]=>
  object(fruit)#1 (2) {
    ["name"]=>
    string(5) "apple"
    ["colour"]=>
    string(5) "green"
  }
  [1]=>
  object(fruit)#2 (2) {
    ["name"]=>
    string(4) "pear"
    ["colour"]=>
    string(6) "yellow"
  }
  [2]=>
  object(fruit)#3 (2) {
    ["name"]=>
    string(10) "watermelon"
    ["colour"]=>
    string(4) "pink"
  }
} 
  

PDO :: FETCH_INTO:要将行提取到类的现有实例中,请使用PDO :: FETCH_INTO并将该对象作为第二个参数传递。

     

必须将列名称声明为公共成员,或   脚本会死。

 <?php
class Test
{
    protected $cols;

    function __set($name, $value) {
        $this->cols[$name] = $value;
    }

    function __get($name) {
        return $this->cols[$name];
    }
}

$obj = new Test();
$db = PDOTest::factory();
$stmt = $db->prepare("select * from test");
$stmt->setFetchMode(PDO::FETCH_INTO, $obj);
$stmt->execute();

foreach ($stmt as $a) {
    print_r($a);
}

print_r($obj); // contains the same values as the last iteration above
?>