Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

pdo

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

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.

How does this work?

like image 580
PHPDEV Avatar asked May 30 '13 21:05

PHPDEV


People also ask

What is PDO :: Fetch_assoc?

PDO::FETCH_ASSOC. Returns an array indexed by column name as returned in your result set. PDO::FETCH_BOTH (default) Returns an array indexed by both column name and 0-indexed column number as returned in your result set.

What does PDO fetchAll return?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.


1 Answers

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

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

Array (     [email] => '[email protected]'     [password] => 'yourpassword' ) 

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

$user['email']; 

and for 'password':

$user['password']; 
like image 128
George Cummins Avatar answered Sep 20 '22 04:09

George Cummins