相关文章推荐
健壮的热带鱼  ·  python - MongoDB ...·  1 年前    · 
淡定的金鱼  ·  检查网站正常 - 知乎·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

Thank you everyone. My knowledge of PDO was not very good and now I fully understand how to read this stuff. – PHPDEV May 30, 2013 at 22:16

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] => 'youremail@yourhost.com'
    [password] => 'yourpassword'

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

$user['email'];

and for 'password':

$user['password'];
                @George Cummins : sorry for seeing and contradicting your comment years after:rowcount() is only to count affected rows (insert, update, delete). To count result sets, it may work with some databases (like mysql), but there's no guarantee at all, see php.net/manual/en/pdostatement.rowcount.php. Use fetchAll() then count array entries with count(), or if the count is the only needed value, query for a select count (*).
– fpierrat
                Dec 8, 2016 at 15:36

Loop through the array like any other associative array:

while($data = $datas->fetch(PDO::FETCH_ASSOC)){
    print $data['title'] . '<br>';
$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);
echo '<pre>' . $resultset . '</pre>';
                Given that we're specifically talking about PHP, the terms list and dictionary are entirely and unequivocally incorrect. PHP has neither lists nor dictionaries. It has arrays, and associative arrays.
– CGriffin
                Jan 23, 2019 at 17:08

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

Why do you recommend that? Why is it better or what is the advantage? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 22, 2021 at 23:50 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

$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 = $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 = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];

consider the following code script, will help.

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.