php 如何读取 fetch(PDO::FETCH_ASSOC);

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16846531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:47:09  来源:igfitidea点击:

How to read fetch(PDO::FETCH_ASSOC);

phppdo

提问by PHPDEV

I am trying to build a web application using PHP and I am using memcached for storing user data from the DB.

我正在尝试使用 PHP 构建一个 Web 应用程序,并且我正在使用 memcached 来存储来自数据库的用户数据。

For example lets 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 $uservariable and get the data out of it. I will need to be able to read the email and password column.

我不太确定如何读取$user变量并从中获取数据。我需要能够阅读电子邮件和密码栏。

I was hoping that someone could explain to me how this works.

我希望有人可以向我解释这是如何工作的。

Thanks

谢谢

回答by George Cummins

PDOStatement::fetchreturns a row from the result set. The parameter PDO::FETCH_ASSOCtells PDO to return the result as an associative array.

PDOStatement::fetch从结果集中返回一行。该参数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] => '[email protected]'
    [password] => 'yourpassword'
)

To read data from the 'email' column, do:

要从“电子邮件”列中读取数据,请执行以下操作:

$user['email'];

and for 'password':

对于“密码”:

$user['password'];

回答by Ben Racicot

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>';

回答by Kit

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 listof a dictionary

返回一个列表一个的字典

回答by Miro Markaravanes

PDO:FETCH_ASSOCputs the results in an array where values are mapped to their field names.

PDO:FETCH_ASSOC将结果放在一个数组中,其中值映射到它们的字段名称。

You can access the namefield like this: $user['name'].

您可以name像这样访问该字段:$user['name']

I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

我建议使用PDO::FETCH_OBJ. 它获取对象中的字段,您可以像这样访问:$user->name

回答by Akatosh

To read the result you can read it like a simple php array.

要读取结果,您可以像读取简单的 php 数组一样读取它。

For example, getting the namecan be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC)will only return 1 tuple tho. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC). You can go through the multidimensional array and get the values just the same.

例如,获取name可以像$user['name'],等等。该方法fetch(PDO::FETCH_ASSOC)只会返回 1 个元组。如果要获取所有元组,可以使用fetchall(PDO::FETCH_ASSOC). 您可以遍历多维数组并获得相同的值。

回答by antelove

/* 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'];