display multiple rows from mysql in a php function - php

I have this PHP function i am using to retrieve rows from a mysql database:
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence ");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results=array();
foreach($records as $results) {
return $results;
}
here i am calling the function:
$test = AdminUserSessionID2('2');
echo $test["forename"];
but it is only displaying one row, what have i done wrong which is making it not display all rows?

Why return in foreach? Of course it will return just the first row. It's like saying foreach(rows as row){ return row; }.
<?php
function MyFunction($user_sequence){
global $pdo_conn;
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence;");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $records;
}
var_dump(MyFunction($user_sequence));
?>

You are assigning results as an empty array.
Then assigning it as the first item of records and returning it.
Try:
foreach($records as $row) {
array_push($results, $row)
}

You can't return multiple data/results in a foreach loop, because the first return will end the function. It's better to return the full array/records and do a foreach loop outside the function.

The $results array is getting returned, which should then be looped outside of the function

Try this:
function AdminUserSessionID2($user_sequence){
$stmt = $pdo_conn->prepare('SELECT * from admin where sequence > :sequence');
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $records;
}

No-one has pointed out that return will exit your current function directly preventing any further processing, and this is why you get just one row output. Your specific code based on what you want to achieve would be:
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence ");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results=array();
foreach($records as $results) {
$test = AdminUserSessionID2('2');
echo $test["forename"];
}
See: http://php.net/return

Related

PHP - Execute select query and loop through results

I am developing a web service using PHP. I am having some trouble while executing the select query. This is the code I'm using.
DB_Functions.php
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
return mysql_fetch_array($result,true);
} else {
return false;
}
}
GetCompanies.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$companies = array();
//$rows = $db->getCompanies();
while ($row = $db->getCompanies()) {
echo $row['companyName'];
$rowArr = array();
$rowArr['CompanyName'] = $row['companyName'];
$rowArr['CompanyID'] = $row['companyId'];
//array_push($companies, $rowArr);
$companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>
But the problem is in GetCompanies.php file the while loop is runs endless. The code appears to be ok. Any help would be appreciated.
When you do while ($row = $db->getCompanies()) { you are running the entire query over again and returning the 1st row each time. mysql_fetch_array returns one row.
What you need to do is have getCompanies() loop over all the rows and return an array.
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
$ret = array();
while($row = mysql_fetch_assoc($result)){
$ret[] = $row;
}
return $ret;
} else {
return false;
}
}
Now, getCompanies() will return you an array that you can just foreach over:
$rows = $db->getCompanies();
foreach($rows as $row){
// ...
}
Change your while loop declaration to something like
foreach($rows as $row) {}
And as Pavlin said, move the function call to getCompanies() outside the loop.
Also, how about modifying the query to select a particular set of fields from the database and directly sending them as the response without doing any additional processing?
Since you are implementing Select query without any condition(where clause). And since the company table has data it would always return true in the while loop this makes the while loop an infinite loop. For while to work properly the condition should become false to exit the loop.
Its not a programming flaw its a logical one.
The php docs have all the information you need. You're using the wrong function:
mysqli_fetch_array — Fetch a result row as an associative, a numeric
array, or both
vs
mysqli_fetch_all — Fetches all result rows as an associative array, a
numeric array, or both
Just change your return statement to
return mysqli_fetch_all($result);
or
return mysqli_fetch_all($result, MYSQLI_ASSOC);
to get an associative array.
And of course, you need to move your getCompanies call outside of the loop.
NOTE
php mysql_* functions have been depricated since version 5.5.* and are going to be removed from the language soon. You should look into mysqli_* or PDO.

PHP PDO FetchAll vs Fetch

I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.

php MySQLi fetch results best practice

These are my two methods for querying a database.
This is my first method that saves all the results in an array. Then i use a foreach loop to loop through the array.
public function query($query) {
$rows = array();
if ($result = $this->mysqli->query($query)) {
if($result->num_rows > 1) {
while ($item = $result->fetch_assoc()) {
$rows[] = $item;
}
//jo else sepse nxjerr error kur ska asnje row i ben fetch kur ska row.
} else if($result->num_rows == 1) {
$rows = $result->fetch_assoc();
}
return $rows;
} else {
echo "error";
}
}
Then to output I use:
$run_query = $db->query($query);
foreach ((array)$runk_query as $data) {
....
This is my second method:
$query = $db->query("SELECT * FROM ...");
while($run_query = mysqli_fetch_array($query)) {
//OUTPUT data.
....
}
I notice that in many cases I need to output the results so I think using the first method is bad because I use once the while loop and then I use again a foreach loop so the work is done twice but the second way is not very OOP.
Can anyone suggest me the best method of this or if possible another better method?
You can likely replace you entire first function with a call to mysqli_fetch_all() instead of iterating through each record with fetch_assoc(). This way you don't have to build your array result by result.
You can then run through all the results with your second foreach as per usual.
See: http://www.php.net//manual/en/mysqli-result.fetch-all.php
Alternatively if you were using PDO you could use fetchAll()
See: http://www.php.net/manual/en/pdostatement.fetchall.php

how do we use mysqli properly to fetch all the records from table?

I am getting only one row, can someone please tell me how to get all the data from the table column of my database table ?
public function getCategories(){
$result = $this->db->query('SELECT * FROM newscat');
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
return $rows;
}
}
You're returning from within the loop. That will break it in the first round.
return outside the loop.
do the minor change
public function getCategories(){
$result = $this->db->query('SELECT * FROM newscat');
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
Your problem is the return $rows;. It should reside after the while. The thing is that it will enter the while, put the first row in the array, and then immediately return it. What you want is to let the while do its thing, and after the it finished, return the array.
If you are using mysqli.
Then you can use its apiFfetch_all to get all the rows at once.
For example :
$array=$result->fetch_all(MYSQLI_ASSOC);
The above code will get all associated rows in the corresponding array.

return variables from array using a function

I retrieve data from database using this query:
SELECT * FROM tickets_departement_groups WHERE group_id = '{$user_group}'
$user_group is already defined, and I fetch the data using mysql_fetch_array, like this:
foreach ($query->result_array() as $row)
{
return $row['departement_id'];
}
All this is under a function called get_departement_id(), So when I do echo get_departement_id();
it prints last departement ID, but I have many of them. What I want to do is to output all the department IDs for a given query.
create and array and return the array?
$id_list = array();
foreach($query->result_array() as $row){
$id_list[] = $row['departement_id'];
}
return $id_list;

Categories