Fetch all results from database using mysqli [duplicate] - php

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 years ago.
please check out my code below. With that class I am able to display results like so:
$connectTest = new testResults();
$test = $connectTest->grabResults(test, id, id);
echo $test['id'];
echo $test['name'];
echo $test['address'];
In my database I have several fields in the "test" table. I go to my page using index.php?id=1. With this I am displaying just the results from one row because it grabs all results WHERE id = 1.
What I need is the class below to display multiple results. It just displays one row. But if I have multiple rows with id = 1 I would like to display these results, but I cannot get it to work. I have tried a lot of things but I always end up with just one result.
class:
class testResults
{
public function grabResults($table, $field, $id)
{
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
$resultData[] = array();
if(!$result)
{
return false;
}
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
foreach ($rows as $resultData)
{
return $resultData;
}
}
}
Edit:
Array ( [id] => 25 [name] => test [status] => 1 )
Array ( [id] => 25 [name] => test [status] => 3 )
Array ( [id] => 25 [name] => test [status] => 5 )
Array ( [id] => 25 [name] => test [status] => 4 )
Array ( [id] => 26 [name] => test [status] => 1 )
Array ( [id] => 26 [name] => test [status] => 3 )
Array ( [id] => 27 [name] => test [status] => 1 )
Array ( [id] => 27 [name] => test [status] => 3 )
Array ( [id] => 27 [name] => test [status] => 5 )
Array ( [id] => 27 [name] => test [status] => 4 )
Array ( [id] => 27 [name] => test [status] => 2 )
Array ( [id] => 27 [name] => test [status] => 4 )
Array ( [id] => 27 [name] => test [status] => 1 )
I am getting results as above, any way to easily display these results in an echo? For each id there are different results, so results will vary with each query. So I would like to display results in a table for example like so:
echo '<table>
<tr>
<td>$id</td>
<td>$name</td>
<td>$status</td>
</tr>
</table>';
So all results will be displayed like in a while loop.

You can just return the array from function and then loop in your script
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
The you can loop in your script
$test = $connectTest->grabResults(test, id, id);
foreach($test as $value)
{
print_r($value);
}
Upon OP edit
If you need to print them separate you can access all elements with variable name and scopes with keys as follow
$test = $connectTest->grabResults(test, id, id);
echo '<table>';
foreach($test as $value)
{
echo '<tr>
<td>'.$value['id'].'</td>
<td>'.$value['name'].'</td>
<td>'.$value['status'].'</td>
</tr>';
}
echo '</table>';

Since you are passing the full resultset to another layer for processing, you can skip the loop to generate an array of associative arrays from the resultset.
class testResults {
public function grabResults($table, $field, $id) {
// For the record, I feel a prepared statement is in order here...
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
return $result->fetch_all(MYSQLI_ASSOC); // just in case you wanted to see the column names
}
}
Then when you want to generate an html table from the returned array of associative arrays, use implode() as a flexible solution that doesn't care if you ever change the number of columns being passed in -- it will handle an indefinite number of columns.
if ($resultset = grabResults("tests", "name", "test")) {
echo "<table>";
foreach ($resultset as $i => $row) {
// if (!$i) { echo "<tr><th>" , implode("</th><th>", array_keys($row)) , "</th></tr>"; }
echo "<tr><td>" , implode("</td><td>", $row) , "</td><tr>"
}
echo "</table>";
}

It looks like you are returning a single row of your results with this bit of the function:
foreach ($rows as $resultData)
{
return $resultData;
}
You should just return the whole thing instead.
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;

return inside foreach() iteration means stop right after first iteration. Therefore you will be always getting only the first result.
You'd better write this as:
public function grabResults($table, $field, $id)
{
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}

Related

How to put value to blank array inside foreach loop php

I am using query in foreach loop (according to userType) and after query in foreach loop i am getting
following result
Array
(
[0] => Array
(
[bookingId] => 1
[userId] => 102
[status] => paid
}
[0] => Array
(
[bookingId] => 3
[userId] => 102
[status] => paid
}
[0] => Array
(
[bookingId] => 5
[userId] => 102
[status] => paid
}
...
}
Now i want all result outside foreach loop so i tried with following code but not working,showing me single record istead of multiple
I tried with following code but not working for me
$record=array();
foreach ($result as $key => $row)
{
$query= // mysql query
$rows = $query->result_array();
$record['bookingId']=$rows['0']['bookingId'];
$record['userId']=$rows['0']['userId'];
$record['status']=$rows['0']['status'];
}
echo "<pre>";print_R($record);
Don't you rewrite the value in the array every time?
$record = array();
foreach ($result as $key => $row) {
$query = // mysql query
$rows = $query->result_array();
$record[] = [
'bookingId' => $rows['0']['bookingId'],
'userId' => $rows['0']['userId'],
'status' => $rows['0']['status'],
];
}
echo "<pre>";
print_R($record);
You need to use it something like this.
$record = array();
foreach ($result as $key => $row)
{
$query = // mysql query
$rows = $query->result_array();
$record[]['bookingId'] = $rows['0']['bookingId'];
$record[]['userId'] = $rows['0']['userId'];
$record[]['status'] = $rows['0']['status'];
}
echo "<pre>";print_R($record);
Basically, you're missing updating the index of the array.

Looping through array and get non-repeating values

I have an array of elements which I queried from the mongoDB.
This array has the id of a device and value of this device's consumptions.
For example there are 3 different ids -> 18,5,3 and multiple mixed values.
// first record of 18 so get value.
$row[0]["id"] = 18;
$row[0]["value"] = 100;
// not first record of 18 so ignore and move to the next record
$row[1]["id"] = 18;
$row[1]["value"] = 40;
// first record of 5 so get value.
$row[2]["id"] = 5;
$row[2]["value"] = 20;
// not first record of 18 so ignore and move to the next record
$row[3]["id"] = 18;
$row[3]["value"] = 30;
// first record of 3 so get value.
$row[4]["id"] = 3;
$row[4]["value"] = 20;
//not first record of 5 so ignore and move to the next record**
$row[5]["id"] = 5;
$row[5]["value"] = 30;
// not first record of 18 so ignore and move to the next record
$row[6]["id"] = 18;
$row[6]["value"] = 10;
...
....
What I am trying to do is loop through this $row array and get the most recent value of the id.
For example in above example what I want to return is:
id value
18 100
5 20
3 20
How can I do that kind of logic?
It can be done in several ways. The easiest one is to use a foreach:
$result = array();
foreach ($row as $i) {
if (! array_key_exists($i['id'], $result)) {
$result[$i['id']] = $i['value'];
}
}
# Verify the result
print_r($result);
The output is:
Array
(
[18] => 100
[5] => 20
[3] => 20
)
The same processing, but using array_reduce():
$result = array_reduce(
$row,
function(array $c, array $i) {
if (! array_key_exists($i['id'], $c)) {
$c[$i['id']] = $i['value'];
}
return $c;
},
array()
);
If you want to keep only the first occurrence of each 'id' then just add the values to an aggregate array - but only if they haven't been added already. Then grab the values of the aggregate array.
https://tehplayground.com/NRvw9uJF615oeh6C - press Ctrl+Enter to run
$results = array();
foreach ($row as $r) {
$id = $r['id'];
if (! array_key_exists($id, $results)) {
$results[$id] = $r;
}
}
$results = array_values($results);
print_r($results);
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
Try this
$alreadyfound = []; // empty array
$result = [];
foreach ($row as $item)
{
if (in_array($item["id"], $alreadyfound))
continue;
$alreadyfound[] = $item["id"]; // add to array
$result[] = $item;
}
The result
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
The array_unique() function is exactly what you are looking at.
See the documentation here : array_unique() documentation
Using array_column with an index key will almost do it, but it will be in the reverse order, so you can reverse the input so that it works.
$result = array_column(array_reverse($row), 'value', 'id');

Retrieving data from Multi dimensional Array in Codeigniter

I can't quite get my data from an array, it just shows a blank list of list items when I run my foreach loop.
When I print my array it outputs the following:
Array (
[Description] => Array (
[0] => sidewindo
[1] => sidewindo
[2] => sidewindo
[3] => testing )
[comments] => Array (
[0] => sidewindo
[1] => sidewindo
[2] => sidewindo
[3] => testing )
[Fld_id] => 625
[fld_IsPublic] => Array (
[0] => 1 )
[action] => s
[pk_id] => 7 )
My code so far
public function save_data($data)
{
foreach ($data as $row)
{
foreach ($row['Description'] as $show)
{
echo $show;
}
}
And i have tried the following kind of for loop also to retrieve data from the array. I am trying to retrieve data from the array and update it in another table in the database. This code I have written in my model before passing it to the view.
for($i=0;$i<count($comments);$i++)
{
$this->db->update->update('tblname',array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id'],'fld_description'=>$data['Description'],'fld_comments'=>$data['comments'],'fld_IsPublic'=>$data['fld_IsPublic']),array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id']));
}
}
First of all you should know that echo an array will produce a Notice ( Array to string conversion ), so depending in what environment you are working on you will prefer to use print_r.
Answering your question, before you echo, you should check if it's an array or not
public function save_data($data){
$update = array();
foreach ($data as $key=>$row){
if(is_array($row)){
foreach($row as $key2=>$row2){
$update[$key2] = $row2;
//echo $row2 . "<br>";
}
}else{
$update[$key] = $row;
//echo $row ."<br>";
}
}
}
And now you can use $update to update your table , include this on inside save_data() function, and if you needed, include save_data() inside a foreach. Remember that is recommended to use a where when updating data so:
//$this->db->where('id', $id);
$this->db->update('tblname', $update);
hope that helps
Change Your code from
public function save_data($data)
{
foreach ($data as $row)
{
foreach ($row['Description'] as $show)
{
echo $show;
}
}
to
public function save_data($data)
{
foreach ($data["comments"] as $key=>$row)
{
$data_update = array(
'TK_id' => $data['pk_id'],
'Fld_id' => $data['Fld_id'],
'fld_description' => $data['Description'][$key],
'fld_comments' => $row,
'fld_IsPublic' => $data['fld_IsPublic'][0]
);
$this->db->update('tblname',$data_update,array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id']));
//but this will update single row again and again
//my suggetion is use $this->db->insert('tblname',$data_update); instead
}
}
ANd you will be just fine

Display value of two-dimensional php array in table

I've got an array extracted from MySQL called "$agents", looking like:
Array (
[0] => Array ( [agent] => Agent/1002 [total] => 02:11:07 )
[1] => Array ( [agent] => Agent/1400 [total] => 01:49:53 )
[2] => Array ( [agent] => Agent/1500 [total] => 03:26:29 ) )
Then another MySQL query creates a table as:
while ($row = mysql_fetch_row($q)) {
$result .="<tr><td>".$row[0]."</td><td align=center>".
$row[1]."</td><td align=center>".
$row[2]."</td><td align=center>".
$row[3]."</td><td align=center>".$agents['0']['total']."</tr>";
}
How can I get the 'total' value from the array displayed in the last column of the table?
I want to insert the total for each agent. With an if statement, very simplified, like:
if $row[0] == $agents['0']['agent'] echo $agents['0']['total'] else echo 'NONE'"
Tried with "foreach" loop, but didn't get it to work.
Any ideas/suggestions of how this can be done?
You could initialize a counter above the second fetching. Like this:
$agents = holds your first data fetches from db
$i = 0; // initialize a counter
while ($row = mysql_fetch_row($q)) {
// condition block
if($row[0] == $agents[$i]['agent']) {
$total = $agents[$i]['total']; // if they match, assign the total
} else {
$total = ''; // else just assign an empty string
}
$result .="
<tr><td>".$row[0]."</td>
<td align=center>".$row[1]."</td>
<td align=center>".$row[2]."</td><td align=center>".$row[3]."</td>
<td align=center>".$total."</tr>
";
$i++; // increment
}

Recursive PHP function for adjacency-list display

I have a DB like so:
id text parent
1 Parent 1 0
2 Child of 1 1
3 Sibling 1
4 Another Parent 0
5 A first child 4
So I'm trying to capture a tree structure my listing the parents. I'm aware of the other option (nested sets I think?) but I'm going to stick with this for now. I'm now trying to get the data out of the DB and into a nested array structure in PHP. I have a function like this:
class Data_Manager
{
public $connection = '';
public $collection = array();
function __construct() {
$this->connection = mysql_connect('localhost', 'root', 'root');
$thisTable = mysql_select_db('data');
// error handling truncated
}
function get_all() {
$arr = &$this->collection;
$this->recurseTree('', 0, $arr);
var_dump($arr);
}
function recurseTree($parent, $level, $arrayNode) {
$result = mysql_query('SELECT * FROM tasks WHERE parent="' . $parent . '";');
while ($row = mysql_fetch_array($result)) {
$row['children'] = array(); //where I'd like to put the kids
$arrayNode[$row['id']]= $row;
$this->recurseTree($row['id'], $level+1, $arrayNode[$row['id']]);
}
}
}
So what I'd like to come out with is some kind of nested tree of associative arrays, but I can't figure out quite how to do that. Nothing seems to be writing to the array I pass in, and I'm sort of losing track of myself in the recursion. Can anyone help get me over this last hump that will result in something like:
[
Parent1 => [
children => ['Child of 1', 'Sibling']
],
AnotherParent => [
children => ['First Child']
]
]
And I'm less concerned with the specific form of the output. It will be turned into JSON and I haven't dealt with writing up the client-side handler yet, so no worries on exact structure.
Thanks!
Try this.
$sql = "SELECT * FROM tasks";
$r = mysql_query($sql, $conn);
$arr = array();
while ($row = mysql_fetch_assoc($r))
$arr[] = $row
function build($arrayIn, $parent)
{
$makeFilter = function($p) {return function($x) use ($p) {return $x['parent'] == $p;};};
$f = $makeFilter($parent);
$these = array_filter($arrayIn, $f);
$remaining = array_diff_assoc($arrayIn, $these);
$ans = array();
foreach($these as $cur)
{
$ans[$cur['text']] = build($remaining, $cur['id']);
}
return $ans ? $ans : null;
}
$tree = build($arr, 0)
echo_r($arr);
echo "becomes<br />";
echo_r($tree);
Here is my output:
Array
(
[0] => Array
(
[text] => a
[id] => 1
[parent] => 0
)
[1] => Array
(
[text] => b
[id] => 2
[parent] => 0
)
[2] => Array
(
[text] => c
[id] => 3
[parent] => 1
)
[3] => Array
(
[text] => d
[id] => 4
[parent] => 2
)
[4] => Array
(
[text] => e
[id] => 5
[parent] => 2
)
[5] => Array
(
[text] => f
[id] => 6
[parent] => 3
)
)
becomes
Array
(
[a] => Array
(
[c] => Array
(
[f] =>
)
)
[b] => Array
(
[d] =>
[e] =>
)
)
This bit of pseudo code should help.
function getTasks($parent = 0){
$tasks = array();
$query = mysql_query("select * from table where parent = $parent");
$rows = array();
while(($row = mysql_fetch_assoc($query)) !== FALSE){ $rows[] = $row; }
if(count($rows)){
$tasks[$parent][] = getTasks($parent);
} else {
return $tasks;
}
}
$tasks = getTasks();
You really don't need a recursive function here. Get all the data using one database query and loop over it. It will be much faster then multiple database calls.
Assuming you're storing the data in MySQL, see the answer to this question for instructions on how to write a SELECT statement against an Adjacency List table that returns everything in a hierarchy. In short, use MySQL session variables. Then take the resultset and loop over it, use a stack to push - pop - peek the last parent id to determine indentation of your data structures.
Here is a PHP class I wrote for handling all kinds of Adjacency list tasks.
http://www.pdvictor.com/?sv=&category=just+code&title=adjacency+model

Categories