Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Return All Rows [duplicate]

Tags:

sql

php

pdo

So, right now I have a PHP function that utilizes PDO to return the first row of a specific table. That works fine, but I want to return all of the information, while being able to organize it all.

I have the table zip__admins and I'm trying to return the first_name and last_name from the table. With this information, I have a button on the login page asking the user to select their name (each person gets their own button) to sign in. As of now, I'm returning one result, instead of two results. How can I modify the below code to return two results, and input the data into a templating parameter.

final public function fetchAdminInfo() {
    global $zip, $db, $tpl;

    $query = $db->prepare('SELECT first_name, last_name FROM zip__admins');
    $query->execute();

    $result = $query->fetch(PDO::FETCH_ASSOC);

    $tpl->define('admin: first_name', $result['first_name']);
    $tpl->define('admin: last_name', $result['last_name']);
}

Here is my table: ![SQL Table][1]

like image 353
Intact Dev Avatar asked Aug 26 '13 01:08

Intact Dev


People also ask

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.

What PDO execute return?

PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement. PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query().

How to get row count in PDO?

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of matching rows.

How to fetch all in PHP?

To fetch data from a result set: Fetch data from a result set by calling one of the fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.


1 Answers

You need to use fetchAll()

$result = $query -> fetchAll();

foreach( $result as $row ) {
    echo $row['first_name'];
    echo $row['last_name'];
}
like image 132
Ravi K Thapliyal Avatar answered Oct 11 '22 02:10

Ravi K Thapliyal