简体   繁体   English

如何阅读“获取(PDO::FETCH_ASSOC);”

[英]How to read "fetch(PDO::FETCH_ASSOC);"

I am trying to build a web application using PHP and I am using Memcached for storing user data from the database.我正在尝试使用 PHP 构建一个 web 应用程序,并且我正在使用Memcached来存储数据库中的用户数据。

For example, let's say that I have this code:例如,假设我有这段代码:

 $sql    = "SELECT * FROM users WHERE user_id = :user_id";
$stmt   = $this->_db->prepare($sql);
$result = $stmt->execute(array(":user_id" => $user_id));
$user   = $stmt->fetch(PDO::FETCH_ASSOC);

I am not really sure how to read the $user variable and get the data out of it.我不太确定如何读取$user变量并从中获取数据。 I will need to be able to read the email and password column.我需要能够读取 email 和密码列。

How does this work?这是如何运作的?

PDOStatement::fetch returns a row from the result set. PDOStatement::fetch从结果集中返回一行。 The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.参数PDO::FETCH_ASSOC告诉 PDO 将结果作为关联数组返回。

The array keys will match your column names.数组键将匹配您的列名。 If your table contains columns 'email' and 'password', the array will be structured like:如果您的表包含列 'email' 和 'password',则数组的结构将如下所示:

Array
(
    [email] => 'youremail@yourhost.com'
    [password] => 'yourpassword'
)

To read data from the 'email' column, do:要从“电子邮件”列中读取数据,请执行以下操作:

$user['email'];

and for 'password':和“密码”:

$user['password'];

Loop through the array like any other Associative Array:像任何其他关联数组一样循环遍历数组:

while($data = $datas->fetch( PDO::FETCH_ASSOC )){ 
     print $data['title'].'<br>'; 
}

or或者

$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);

echo '<pre>'.$resultset.'</pre>';

Method方法

$user = $stmt->fetch(PDO::FETCH_ASSOC);

returns a dictionary .返回一个字典 You can simply get email and password:您可以简单地获取电子邮件和密码:

$email = $user['email'];
$password = $user['password'];

Other method其他方法

$users = $stmt->fetchall(PDO::FETCH_ASSOC);

returns a list of a dictionary返回字典列表

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names. PDO:FETCH_ASSOC将结果放在一个数组中,其中的值映射到它们的字段名称。

You can access the name field like this: $user['name'] .您可以像这样访问name字段: $user['name']

I recommend using PDO::FETCH_OBJ .我建议使用PDO::FETCH_OBJ It fetches fields in an object and you can access like this: $user->name它获取对象中的字段,您可以像这样访问: $user->name

To read the result you can read it like a simple php array.要读取结果,您可以像读取简单的 php 数组一样读取它。

For example, getting the name can be done like $user['name'] , and so on.例如,可以像$user['name']等那样获取name The method fetch(PDO::FETCH_ASSOC) will only return 1 tuple tho.方法fetch(PDO::FETCH_ASSOC)只会返回 1 个元组。 If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC) .如果要获取所有元组,可以使用fetchall(PDO::FETCH_ASSOC) You can go through the multidimensional array and get the values just the same.您可以遍历多维数组并获得相同的值。

/* Design Pattern "table-data gateway" */ /* 设计模式“表数据网关” */

class Gateway
{
    protected $connection = null;

    public function __construct()
    {
        $this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
    }

    public function loadAll()
    {
        $sql = 'SELECT * FROM users';
        $rows = $this->connection->query($sql);

        return $rows;
    }

    public function loadById($id)
    {
        $sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
        $result = $this->connection->query($sql);

        return $result->fetch(PDO::FETCH_ASSOC);
        // http://php.net/manual/en/pdostatement.fetch.php //                   
    }
}

/* Print all row with column 'user_id' only */ /* 仅打印包含“user_id”列的所有行 */

$gateway  = new Gateway();
$users    = $gateway->loadAll();

$no = 1;
foreach ($users as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
    $no++;
}

/* Print user_id = 1 with all column */ /* 用所有列打印 user_id = 1 */

$user = $gateway->loadById(1);

$no = 1;
foreach ($user as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value . '<br />';
    $no++;
}

/* Print user_id = 1 with column 'email and password' */ /* 使用列“电子邮件和密码”打印 user_id = 1 */

$user = $gateway->loadById(1);

echo $user['email'];
echo $user['password'];

consider the following code script, will help.考虑以下代码脚本,会有所帮助。

$stm = $accountdb->query($sql);
    $result = $stm->fetchAll(PDO::FETCH_ASSOC);
       $number = $stm->rowCount();        
            $json = json_encode($result, JSON_UNESCAPED_UNICODE);
                header("Content-type: application/json");
                    echo '{"total" : "' . $number . '","records" : ' . $json . '}';

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

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