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]
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.
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().
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.
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.
You need to use fetchAll()
$result = $query -> fetchAll();
foreach( $result as $row ) {
echo $row['first_name'];
echo $row['last_name'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With