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.

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?


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

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.

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

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


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

For example, getting the name can be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC) will only return one tuple though. 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.