Instantiating objects foreach and mysqli results - php

hopefully this can make sense.
I want to be able to do something like this
<?php
require_once("inc/database_connection.php");
require_once("classes/Users.php");
$users = Users::GetAllUsers($dbConn);
foreach($users as $user) {
echo $user->GetUserName();
}
?>
I see that it is available in code igniter's result() set function - http://www.codeigniter.com/user_guide/database/results.html
but I would really like to add it into my database class.

The GetAllUser method should contain something like:
$res = mysqli_query(...);
$results = array();
while ($row = mysqli_fetch_assoc($res)) {
$results[] = new User($row['userid'], $row['username'], $row['email'], ...);
}
return $results;

Related

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;
}

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

Make fetch_assoc match fetch_all exactly

How do I match exactly the output of fetch_all with a loop using fetch_assoc? I have built code around fetch_all but my Bluehost server with PHP 5.4 isn't sufficient to run it (I'm talking to them about it). Here is what I've been using and it doesn't work:
public function getAllRecords($query) {
$results = array();
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);
while ($row = $r->fetch_assoc()) {
$results[] = $row;
}
return $results;
}
EDIT
This function works but only returns one result:
public function getOneRecord($query) {
$r = $this->conn->query($query.' LIMIT 1') or die($this->conn->error.__LINE__);
return $result = $r->fetch_assoc();
}
To have $results containing the output exactly like that of of fetch_all, you can use this loop:
while ($row = $r->fetch_assoc()) {
$results[] = array_values($row);
}
or just using fetch_row in the loop:
while ($row = $r->fetch_row()) {
$results[] = $row;
}
OK, I don't know why my question was down-voted, it is legitimate. fetch_all as I was using it before, returns an array of rows as arrays. All my functions were based on parsing these arrays to their key values.
fetch_assoc returns an associative array, which is interpreted in Javascript as an object. Of course, my array-based parsing functions don't like that and that also means that fetch_assoc in a loop is NOT equivalent to fetch_all.
What is equivalent is fetch_row. The correct answer:
public function getAllRecords($query) {
$results = array();
$r = $this->conn->query($query) or die($this->conn->error.__LINE__);
while ($row = $r->fetch_row()) {
$results[] = $row;
}
return $results;
}

Rewrite mysqli_fetch_all() to get the same result

Since the servers version is older than 5.3.0, I need to rewrite the following piece of function to do the same as it does now:
else {
$res = mysqli_query($_con, "SELECT * FROM house");
$row = mysqli_fetch_all($res, MYSQLI_ASSOC);
return $row;
}
In html I call it like this:
$results = getResults();
foreach ($results as $value) {
echo $value['Title']." / "; echo $value['Version'];
}
How can I call the results in my html the same way but with different function?
EDIT: I want to get all of the results from table "house" but without the use of function mysqli_fetch_all()
It's just a simple loop that calls mysql_fetch_array() and collects all the rows in an array.
function mysqli_fetch_all($res, $mode) {
$array = array();
while ($row = mysql_fetch_array($res, $mode)) {
$array[] = $row;
}
return $array;
}

php function in a while Loop

i searched all over the web or i just don't see it.
I want to do the following:
<?php
function abc(){
$sql = "SELECT * FROM table";
$result = mysql_fetch_assoc($sql);
$data = mysql_fetch_assoc($result);
}
?>
<? while(abc()) : ?>
<?=article_title()?>
<?=article_content()?>
<?=endwhile;?>
Could somebody give me a direction and/or example?
Thank you very much
PHP does not have generator/iterator functions, so you cannot do that.
You can however return an array and iterate over that array:
function abc() {
// ...
$rows = array();
while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
return $rows;
}
foreach(abc() as $row) {
// do something
}
If the functions you call need access to the row, pass it as an argument. Using global variables for it would be very bad/nasty
have you tried to do something like that?
<?php
function getData(){
//get the data from the database
//return an array where each component is an element found
}
$elems = getData();
foreach($elems as $e){
doSomethingWith($e);
}

Categories