简体   繁体   English

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

[英]What is difference between PDO::FETCH_CLASS and PDO::FETCH_INTO

I can't find any difference between PDO::FETCH_CLASS and PDO::FETCH_INTO. 我找不到PDO :: FETCH_CLASS和PDO :: FETCH_INTO之间的任何区别。 Can you show me an example about what is difference between them? 您能举一个例子说明它们之间的区别吗?

see this PHP PDO fetching into objects 看到这个PHP PDO获取对象

and example below 和下面的例子

<?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;
}

PDO::FETCH_CLASS: Returns instances of the specified class, mapping the columns of each row to named properties in the class. 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);
?>

The above example will output something similar to: 上面的示例将输出类似于以下内容的内容:

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: To fetch the rows into an existing instance of a class, use PDO::FETCH_INTO and pass the object as the second parameter. PDO :: FETCH_INTO:要将行提取到类的现有实例中,请使用PDO :: FETCH_INTO并将该对象作为第二个参数传递。

The class must have the column names declared as public members, or the script will die. 该类必须具有声明为公共成员的列名,否则脚本将消失。

 <?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
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM