如何读取“fetch(PDO::FETCH_ASSOC);"

2021-12-26 00:00:00 php pdo

我正在尝试使用 PHP 构建 Web 应用程序,并且正在使用 Memcached 进行存储来自数据库的用户数据.

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

例如,假设我有这个代码:

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

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

I am not really sure how to read the $user variable and get the data out of it. I will need to be able to read the email and password column.

这是如何工作的?

推荐答案

PDOStatement::fetch 从结果集中返回一行.参数 PDO::FETCH_ASSOC 告诉 PDO 将结果作为关联数组返回.

PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.

数组键将匹配您的列名.如果您的表包含列 'email' 和 'password',则数组的结构如下:

The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:

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

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

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

$user['email'];

和密码":

$user['password'];

相关文章