php function in a while Loop - php

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

Related

How can I return multiple objects in a function in php and then display them

public function getdata()
{
$ctrObj = new Country();
$result = $ctrObj->ctrydata($this->table);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
return $row;
}
}
}
$ctryObj = new CountryController();
$countries = $ctryObj->getdata();
print_r($countries);
when I print_r($countries); then I can see only one object but if I print that in function mentioned above I found all objects.
You could save results in an array and return it:
public function getdata()
{
$data = []; // Init array
$ctrObj = new Country();
$result = $ctrObj->ctrydata($this->table);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
$data[] = $row; // Populate it
}
}
return $data; // Return it
}
Because you return only one result, you can change like this
public function getdata()
{
$ctrObj = new Country();
$result = $ctrObj->ctrydata($this->table);
$rows = [];
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
return $rows;
}
You can yield it :
public function getdata()
{
$ctrObj = new Country();
$result = $ctrObj->ctrydata($this->table);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_array($result)) {
yield $row;
}
}
}
You would use it like this (with a lot of benefits for memory...) :
$ctryObj = new CountryController();
foreach ($ctryObj->getdata() as $country) {
print_r($country);
}
Edit : I've learned with PDO and never been in contact with mysqli so I've tried to find an equivalent to fetchAll(), and apparently, you have a fetch all function also (http://php.net/manual/fr/mysqli-result.fetch-all.php).
I think your code would look like that :
public function getdata()
{
$ctrObj = new Country();
$result = $ctrObj->ctrydata($this->table);
if (mysqli_num_rows($result) > 0) {
$rows = mysqli_fetch_all($result);
return $rows;
}
}
This looks more efficient that getting all your objects one by one to bind them into an array (as it's done by php natively). Anyway, use yield if you don't want to duplicate the buffer of results (one for mysql side, the other one for php side)

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

PHP Array not being delivered

I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}

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

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Categories