PDO ForEach Loop in array (PHP) - php

I want to have all results from my database in one array
my function:
function GetWinkelProduct($g_Winkel) {
global $g_Conn;
$l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
$l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
$l_Stmt->execute();
$l_qurries = new dbquery();
$l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);
while($l_Row = $l_Stmt->fetch(PDO::FETCH_ASSOC)){
$out = array();
foreach($l_Row as $product){
$out[] = $product['pd_id'];
}
}
return $out;
}
other page: <?php print_r($l_qurries->GetWinkelProduct($g_Winkel)); ?>
only I get the first result in the array and when I do $product['pd_id'] I get only the last result.

Try this...
Change fetch to fetchAll in while loop and renove foreach inside while loop
function GetWinkelProduct($g_Winkel) {
global $g_Conn;
$l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
$l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
$l_Stmt->execute();
$l_qurries = new dbquery();
$l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);
while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
$out = array();
$out[] = $l_Row ['pd_id'];
}
return $out;
}
ref:http://php.net/manual/en/pdostatement.fetchall.php

You must initialize the array outside the while loop and you don't need the foreach.
that way you are creating a new array every time the while iterates, that way you end up replacing the array.
$out = array();
while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
$out[] = $l_Row['pd_id'];
}
return $out;

Related

php + mysql query returning only a single row (std class) from class function

Can you tell me why this returns only the last row of my query?
As you see I'm extracting as std class. Also I already tried different approaches like a foreach key=>value inside the while but it does not help. I can't populate $out correctly.
class myclass {
function Query($sql){
$results = $this->db->query($sql);
if (mysqli_num_rows($results)<1){
throw new Exception('NoResults');
}
$out = new stdClass;
while ($r = $results->fetch_object()){
$out = $r;
}
return $out;
$out = null;
}
}
}
---------------
$client = new myclass;
$sql = "SELECT * FROM books";
$q = $client->Query($sql);
print_r($q);
You just need to change those lines:
$out = new stdClass;
while ($r = $results->fetch_object()){
$out = $r;
}
to those ones:
$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
array_push($out, $r); // add to the array the current object
}
return $out; //return the array with the objects
You are overwriting $out at every iteration of the while, so you'll have only the last result in the return. You could use an array and append the results (it could be an array of stdClass objects), and then you'll be able to work with it with a simple loop
class myclass {
function Query($sql){
$results = $this->db->query($sql);
if (mysqli_num_rows($results)<1){
throw new Exception('NoResults');
}
//copied this piece of code from #Berto99 answer from this same question
$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
array_push($out, $r); // add to the array the current object
}
return $out; //return the array with the objects
}
}
---------------
$client = new myclass;
$sql = "SELECT * FROM books";
$q = $client->Query($sql);
foreach($q as $resultLine){
//do whatever you need to do here
}
Your $r is object. You dont need stdClass. You need to add your objects to $out array.
function Query($sql)
{
$results = $this->db->query($sql);
if (mysqli_num_rows($results) < 1) {
throw new Exception('NoResults');
}
$out = new stdClass;
$i=0;
while ($r = $results->fetch_object()){
$out->{$i} = $r;
$i++
}
return $out;
}

Retrieve data with foreach from return array function

I'm having troubles with my function and how to retrieve the data. Here is what i got.
public function getImages()
{
$array = array();
//Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
return $array;
}
}
Now I'm calling this function but i can not use foreach to access the array.
include "header.html";
include "autoload.php";
spl_autoload_register('my_autoloader');
$users = new User;
$users->getImages();
foreach ($users as $value) {
echo $value["username"];
}
What am I doing wrong? I'm only getting one result but there are many in my database. Or if i call the $array in foreach it says undefined.
A couple things. First, your function is only ever returning an array with one element in it. If you want to finish populating the array, don't return until after the loop:
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
And second, you're trying to iterate over the object which has the function, not the value returned from the function. Get the return value and iterate over that:
$userDAO = new User;
$users = $userDAO->getImages();
foreach ($users as $value) {
echo $value["username"];
}
You just need to put the return statement out of the while loop.
public function getImages() {
$array = array(); //Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
}

Query from query result in foreach

so i have this function
public function GetNearAirport($adr)
{
$acftrange = $this->GetAcftAdr($adr);
$too = array();
foreach ($acftrange as $key) {
$result = $this->GetNearRange($adr,$key->range);
}
The $acftrange give me some rows, and i need to get a new result for each row of $acftrange. But i need all results in one array So I can insert into the html table. Sorry for my english. In foreach the $key->range is a condition for the query to be made.
I assume getNearRange() returns an array. Use array_merge to append $result to $too
foreach ($acftrange as $key) {
$result = $this->GetNearRange($adr,$key->range);
$too = array_merge($too, $result);
}

php function not returning all results from a MySQL query in a foreach

Hey guys I have a little issue with a function that retrieves data from a MySQL Database and then I iterate over the results with a foreach loop, checking a value to see if it is null and if it is, replacing it with another value.
The problem with this function is this, that after returning the data I'm only able to view one record retrieved from the database. Probably something simple but it's beyond me.
I would like to do this before passing it to the controller or view. Maybe this isn't possible with the foreach loop? What am I missing?
Here is an example of my code.
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
}
return $new_data;
}
Hopefully someone can help me with this? Thanks!
At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:
$rows = array()
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$rows[] = $new_data;
}
return $rows;
This way every row returned from the database will be added to an array named $rows. At the end you have to return your new array.
You are overwriting $new_data each iteration. Try this
$new_data = new stdClass
...
$all_data[] = $new_data;
Instead of checking for null value in the code, you could just use a IFNULL statement in the SQL query, this does separate the logic a bit but it might just be worth it in this case.
The function returns only the last row in the result because the new_data variable is overwritten in every step of your loop. Declare new_data an array at the start of your function and add rows as array elements
...
$new_data[] = new stdClass;
...
Each iteration of the foreach overwrites $new_data so in the end when the function returns, only the last fetched row will be returned. To return more than one row you could store all the rows in an array and then return the array in the end. It would look something like this:
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
$data = array();
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$data[] = $new_data;
}
return $data;
}
To be able to use this function you have to change the code that uses it to loop through the array of objects.

add array element to row returned from sql query

I want to add an additional value into an array before passing it to json_encode function,
but I can't get the syntax right.
$result = db_query($query);
// $row is a database query result resource
while ($row = db_fetch_object($result)) {
$stack[] = $row;
// I am trying to 'inject' array element here
$stack[]['x'] = "test";
}
echo json_encode($stack);
If it's an array you can directly add a value:
$row['x'] = 'test';
$stack[] = $row;
if it's an object you can add another property:
$row->x = 'test';
$stack[] = $row;
if you want to keep the object and the extra value separated:
$data = array($row, 'x' => 'test');
$stack[] = $data;
but this does work.
$stack[] = $row;
$row->x = 'test';
How about something like:
$row['x'] = 'test';
$stack = $row;

Categories