PDO Return All Rows [duplicate] - php

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
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]

You need to use fetchAll()
$result = $query -> fetchAll();
foreach( $result as $row ) {
echo $row['first_name'];
echo $row['last_name'];
}

Related

Remove Indexes from json_encode output [duplicate]

This question already has answers here:
sql PDO fetchall duplicate object keys?
(2 answers)
Closed 2 years ago.
I've been searching this site and beating my brains out over trying to print_r a json_encode result without including the indexes. Nothing I've found has helped.
Here's the PHP/MySQL function to get data from the database:
public function listGuestsAll() {
if(is_null($this->pdo)) {
$this->msg = 'Connection Failed!';
return [];
} else {
$pdo = $this->pdo;
$stmt = $pdo->prepare('SELECT user_id, name_first, name_last, email_address, user_role FROM guestList');
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
...and here's the print_r code:
print_r(json_encode($user->listGuestsAll()));
...and here's the output:
[
{
"user_id":"1",
"0":"1",
"name_first":"John",
"1":"John",
"name_last":"Doe",
"2":"Doe",
"email_address":"john#doe.com",
"3":"john#doe.com",
"user_role":"1",
"4":"1"
},
{
"user_id":"2",
"0":"2",
"name_first":"Jane",
"1":"Jane",
"name_last":"Doe",
"2":"Doe",
"email_address":"jane#doe.com",
"3":"jane#doe.com",
"user_role":"1",
"4":"1"
}]
How do I get it to output without the repeating field indexed as 0:1, 1:John, 2:Doe, 3:john#doe, 4:1, etc?
Thanks in advance!
You're using this to fetch the rows:
$result = $stmt->fetchAll();
The documentation says that the default fetch mode is PDO::FETCH_BOTH which means the result is returned with both column names as keys and numeric keys.
You can specify a fetch mode. To fetch the row only indexed by numeric keys, use:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
To fetch the row only indexed by column names, use:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can also change the default globally so it affects all your fetches when you don't specify a fetch mode:
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_NUM);
You should read:
https://www.php.net/manual/en/pdostatement.fetch.php
https://www.php.net/manual/en/pdostatement.fetchall.php
https://www.php.net/manual/en/pdo.setattribute.php

PHP Get the class constructor dynamically and call it to create a new instance [duplicate]

This question already has answers here:
Convert PDO resultset to array of objects
(5 answers)
Closed 2 years ago.
I´m trying to get all records from the database and then instantiate a new object with the data from each one:
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results){
for ($i=0; $i<count($results); ++$i){
$strValues = '';
$values = array_values($results[$i]);
for ($j=0; $j<count($values); ++$j){//Extract the values to pass them as arguments to the constructor below
if ($j == 0) $strValues .= $values[$j];
else{
$strValues .= ',';
$strValues .= '"'.$values[$j].'"';
}
}
eval('$result['.$i.'] = new '.get_class($this->instance).'('.$strValues.');');
}
}
The problem is that the object type can vary depending on if I'm querying the users or labels databases, so the call to constructor may be new User(user_id, username, name, surname) or new Label(label_id, name, description, color). The code above runs on the ObjectMapper class, which on creation gets assigned an object type and stores an instance of it in the private instance variable. This way I can get the name of the required constructor with get_class($this->instance).
I finally managed to make it work using an eval as shown, but I've read that this is not a good practice and I would like to know of better and cleaner ways to do it.
This should do what you are trying to achieve. Do not use eval
PDO has plenty of useful fetch modes and they are described here https://phpdelusions.net/pdo/fetch_modes#FETCH_CLASS
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_CLASS, get_class($this->instance));
P.S. Remember to properly whitelist the table name and $order variable.

PHP and PDO from procedural to OOP - empty object [duplicate]

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
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]
You need to use fetchAll()
$result = $query -> fetchAll();
foreach( $result as $row ) {
echo $row['first_name'];
echo $row['last_name'];
}

Return MYSQLi Prepared Statement Query and Bind Results an an Array [duplicate]

This question already has answers here:
How to fetch all in assoc array from a prepared statement?
(4 answers)
Closed 2 years ago.
I want to put the result of a mysqli prepared statement into an array and return the array for use in another page.
The code is presented below.
function getPermission($mysqli , $email) {
if ($stmt = $mysqli->prepare("SELECT m.email , g.permission
FROM members m
INNER JOIN members_groups q ON m.member_id = q.member_id
INNER JOIN groups g on q.group_id = g.group_id
WHERE email = ?"))
{
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_email, $user_perms);
while ($stmt->fetch()) {
echo ' ID: '.$user_email; //prints the results.
}
}
}
I want to place the query results into an array and return the array.
Note: Am using a wamp server with php and mysql in windows 7. I tried to use the $stmt->getresults method, but it returns nothing.
You could try to store it in an array, one by one, in your loop:
$results = array();
while ($stmt->fetch()) {
$results[] = array(
"email" => $user_email,
"perms" => $user_perms
);
}
return $results;
If you need this array in another file, where you include this function, this will work, but if you need it in another request, PHP will have to run this code again to have the array filled.
If you need this array during the session, then consider putting the result in a session variable:
$_SESSION['myarray'] = $results;
Then in the function, first check if the above session variable is set, and if so, immediately return that value. Only when it is not yet set, you perform the rest of the function.

Object can't be converted to a string in MySQLi PHP [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.
You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.

Categories