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


How to read "fetch(PDO::FETCH_ASSOC);"

我正在尝试使用PHP构建一个web应用程序,我使用Memcached从数据库存储用户数据。

例如,假设我有这样的代码:
 $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变量并从中获取数据。我需要能够阅读电子邮件和密码栏。

这是如何工作的?

PDOStatement::fetch从结果集中返回一行。参数PDO::FETCH_ASSOC告诉PDO以关联数组的形式返回结果。

数组键将匹配您的列名。如果您的表包含'email'和'password'列,那么数组的结构将如下所示:

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

从'email'列读取数据,执行:

$user['email'];

和'password':

$user['password'];

像其他关联数组一样遍历数组:

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

$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);
echo '<pre>' . $resultset . '</pre>';
方法
$user = $stmt->fetch(PDO::FETCH_ASSOC);

返回字典。您可以简单地获取电子邮件和密码:

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

其他方法
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
列表

返回一个字典

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

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

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

可以像读取一个简单的PHP数组那样读取结果。

例如,可以像获取$user['name']一样获取name,以此类推。方法fetch(PDO::FETCH_ASSOC)将只返回一个元组。如果想获得所有元组,可以使用fetchall(PDO::FETCH_ASSOC)。您可以遍历多维数组并获得相同的值。

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 //
    }
}

打印所有只有'user_id'列的行

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

打印user_id = 1与所有列

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

打印user_id = 1,列'email and password'

$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];

考虑下面的代码脚本,会有所帮助。

$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 . '}';