renaming array using foreach on controller and view: - php

I'm having a problem, I tried renaming my $query->result_array() using foreach on my controller and called it in view using another foreach to display the result from $query->result_array();
Here's how I did it.
My controller:
I have this user-defined function named logs(), I have a query inside and used $query->result_array() to get the results. Then I renamed it using foreach{} like this code below:
$result = array();
foreach ($query->result_array() as $row) {
$result = array(
"id" => $row['id'],
"name" => $row['name'],
"status" => $row['status'],
"time" => $row['time']
);
}
return $result;
Then I created another user-defined function named filtered_logs() to filter the result from logs() *I filtered it because I have multiple tables to LEFT JOIN it with.
$filtered = array();
$logs = $this->logs();
if ($logs['status'] == "ok") {
$query = $this->db->query("SELECT * FROM table a
LEFT JOIN table b
ON a.image = b.image
LEFT JOIN ....ON...
WHERE a.id = '".$logs['id']."'");
foreach ($query->result_array() as $row){
$filtered = array(
"path" => $row['path'],
"grade" => $row['grade'],
"time" => $logs['time'],
);
}
}
Sending these results to view I used this method, placed on the index of the controller.
$data['logs'] = $this->filtered_logs();
$this->load->view('pages', $data);
Then displayed it on view using these codes:
<?php
foreach ($logs as $row) {
echo $row['id']." </br>";
echo $row['status']." </br>";
echo $row['time']." </br>";
}
?>
but when I do use this way of handling result_array, it gives me an error saying " Illegal string offset '' "
Can someone help me or tell me if there's another way of displaying the results of my queries?

I guess you are missing "[]" after $result array where you are feeding data in it in for each loop and it is causing this error.
It should be like this:
$result = array();
foreach ($query->result_array() as $row) {
$result[] = array(
"id" => $row['id'],
"name" => $row['name'],
"status" => $row['status'],
"time" => $row['time']
);
}
return $result;

This is just an other way of displaying the results try it.
<?php
foreach ($logs as $row) {
echo $row->id." </br>";
echo $row->status." </br>";
echo $row->time." </br>";
}
?>

Related

php pdo json encode array print

When I pull data from the hello database, it just writes the first line, not the other lines, what could be the reason?
I did not know much about php json but did not get any results.
İD 88 NOT FOUND
**database print **
[{"title":"facebook","contact":"facebook adres"},
{"title":"twitter","contact":"twitter adres"}]
database data
id:87 [{"title":"facebook","contact":"facebook adres"},
{"title":"twitter","contact":"twitter adres"}]
id:88
[{"title":"instagram","contact":"instagram adres"},
{"title":"google","contact":"google adres"}]
database function
function menu($menu_title)
{
global $db;
$query = $db->prepare('SELECT * FROM menu WHERE menu_title = :menu_title');
$query->execute([
'menu_title' => $menu_title
]);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
$data = [];
foreach ($result as $key => $value) {
$data += json_decode($value['menu_content'], true);
}
return $data;
}
return null;
}
socialmedia foreach
<?php foreach (menu('sosyalmedya') as $key => $menu): ?>
<?= $menu['title'] ?><br>
<?= $menu['contact'] ?><br>
<?php endforeach; ?>
You're only returning the first element of each JSON array. Append the whole array to the result.
foreach ($result as $value) {
$data = array_merge($data, json_decode($value['menu_content'], true));
}
BTW, don't use SELECT * if you only want the menu_content column. Use SELECT menu_content.

How can I pass on an array of data from the model to the controller and then back to the model?

I'm trying to select rows from my DB table based on information I get from the other rows(previous query). The trouble I'm having is converting the $query->result_array(); in the controller to use it in the model again and subsequently the view.
I've tried to do a foreach loop and returning the $query->result_array(); from the model, this turned out to be problematic as it didn't fit the different stages I have on my website(I have several stages of content).
controller.php
public function firststage() {
$this->load->model('Model');
$get_stage = $_GET["stg"];
$get_results = $this->Model->get_stage_id($get_stage);
foreach ($get_results as $results) {
$id = $results["id"];
}
$data['result'] = $this->Model->stage_results($get_stage, $id);
$this->load->view('stage_view', $data);
}
model.php
public function get_stage_id($get_stage) {
$this->db->where('stage_parent', $get_stage);
$query = $this->db->get('stages');
return $query->result_array();
}
public function stage_results($get_stage, $id) {
$this->db->where('stage_id', $get_stage);
$this->db->where('stage_id', $id);
$query = $this->db->get('stage_contents');
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["id"],
'name' => $row["name"]
);
}
return $rows;
}
Expected the output selection to be based on the first query result, instead I get the Undefined variable: rows when I run all of it. I don't think my view is relevant to this question, but please let me know if you think otherwise!
you get the error
Undefined variable: $rows
because your query doesn't return any result, therefore $rows is not defined
you can resolve this checking if there are rows returned:
if($query->num_rows()){
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
}else {$rows='no records found';}
print_r($rows);die;
this prints either the array (if there are results), or 'no records'
or simply do:
$rows = array();
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
then you get an empty array if there are no results

Data present in multidimensional array are not displayed correctly

I'm trying to get the values from a Query String and add them to an array inside of an array. The output Query String is something like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id[]=1&additional_quantity[]=3&additional_id[]=4&additional_quantity[]=5
I'm getting each additional_id and additional_quantity variables presents in the Query String with the code below. I compare each of the additional_id with the IDs that I have in database table additionals and insert all into an array. The following code exists in my file add_to_cart.php file:
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity,
'additionals' => array()
);
if(isset($_GET['additional_id']) && $_GET['additional_id'] != "")
{
foreach($_GET['additional_id'] as $additional => $value)
{
$additional_id = $value;
if(isset($_GET['additional_quantity'][$additional]))
{
$additional_quantity = $_GET['additional_quantity'][$additional];
if($additional_quantity <= 0 || $additional_quantity > 5)
{
$additional_quantity = null;
}
else
{
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals WHERE additional_id LIKE '{$additional_id}'";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][]['additional_id'] = $additional_id;
$columns['additionals'][]['additional_name'] = $additional_name;
$columns['additionals'][]['additional_price'] = $additional_price;
$columns['additionals'][]['additional_quantity'] = $additional_quantity;
}
}
}
}
}
$_SESSION['cart'][$product_id_session] = $columns;
}
header('Location: products.php?action=added&product_name=' . $product_name);
}
Once everything is added in the cart SESSION, in the cart.php page I'm trying to show the products with their selected additionals and quantities with:
foreach($_SESSION['cart'] as $product)
{
echo "<tr>";
echo "<td>{$product['product_name']}</td>";
echo "<td>${$product['product_price']}</td>";
echo "<td>{$product['quantity']}</td>";
echo "<td>";
foreach($product['additionals'] as $additional)
{
echo "<p>{$additional['additional_quantity']}x{$additional['additional_name']} - {$additional['additional_price']}</p>";
}
echo "</td>";
echo "</tr>";
}
But I'm doing something wrong, I think these two codes are not working properly.
My output is embarrassed, something like this:
Am I doing it by the right way? Maybe I'm not looping right with foreach, or the additionals are not being added with success? Sorry for the mistakes, I never worked with multidimensional arrays before. Is there a way to do what I am intending to? Thanks!
solution as per the comments-
Your issue is caused by $columns['additionals'][] as it is causing each value to being added as its own array. This is solved by added $additional as the array key -
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][$additional]['additional_id'] = $additional_id;
$columns['additionals'][$additional]['additional_name'] = $additional_name;
$columns['additionals'][$additional]['additional_price'] = $additional_price;
$columns['additionals'][$additional]['additional_quantity'] = $additional_quantity;
}
or you could also do-
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][] = array('additional_id' => $additional_id,
'additional_name' => $additional_name,
'additional_price' => $additional_price,
'additional_quantity' => $additional_quantity);
}

MySQL to JSON (For use with NVD3.js)

I'm trying to export the MySQL table below:
id, asof, value
abc, 2013-06-30, 36000000
abc, 2013-12-31, 48000000
abc, 2014-01-31, 51000000
abc, 2014-02-28, 56000000
xyz, 2013-06-30, 26000000
xyz, 2013-12-31, 33000000
xyz, 2014-01-31, 33000000
xyz, 2014-02-28, 36000000
into the following json format for use in the nvd3.js charts:
[
{
"key" : "abc" ,
"values" : [ [ 2013-06-30, 36000000] , [ 2013-12-31, 48000000] , [ 2014-01-31, 51000000] , [ 2014-02-28, 56000000]
},
{
"key" : "xyz" ,
"values" : [ [ 2013-06-30, 26000000] , [ 2013-12-31, 33000000] , [ 2014-01-31, 33000000] , [ 2014-02-28, 36000000]
}
]
I'm sure this is a newbie question but I'm struggling with it. Any guidance would be much appreciated!
Edit:
I've currently been trying to use an array and while statement but have not been able to figure out how to modify the array to so that it can output to the correct json format.
$query= mysqli_query($db,"SELECT id, asof, value
FROM table;"
);
if ( ! $query) {
echo mysqli_error();
die;
}
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
print json_encode($rows);
Probably the most straightforward way of doing this is simply creating a multidimensional array, filling it with data obtained from database and then using json_encode to create a JSON string, which is then sent to the client.
Here is a simple example of a function which will accept an array of items and return a JSON string in the expected format. For simplicity, it is assumed that data was is a 2D array with three columns, but you should modify it to use the format returned by a database query.
function convert($data) {
$intermediate = array();
// This intermediate steps is used just to group all rows with
// the same key
foreach($data as $item) {
list($key, $date, $value) = $item;
$intermediate[$key][] = array($date, $value);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
'key' => $key,
'values' => $values
);
}
return $output;
}
Since you're getting data from database, variable $item inside the first foreach statement might actually be an associate array, so you'll have to write something like $item['key'] to get data for columns in the current row.
If you want to use mysqli_fetch_assoc, then you might try calling the function convert in the following way:
$conn = mysqli_connect('', '', '')
$query = 'SQL you wish to execute'
$result = mysqli_query($conn, $query)
if($result) {
$jsonData = convert($result);
}
However, function itself needs a little bit changing
function convert($result) {
$intermediate = array();
while($item = mysqli_fetch_assoc($result)) {
$key = $item['id'];
$date = $item['asof'];
$value = $item['value'];
$intermediate[$key][] = array($date, $value);
}
// The rest of the function stays the same
}

Need help pulling data out of mysql into a multidimensional array

I am pulling data out of a data base. As I seem to be having trouble with arrays and multidimensional arrays I need some help.
In the database I am pulling the following information:
id, platoon, name, position, status
I need to put all of this into an array.
As there are over 150 names, with many holding the same position.
here is the code I am using:
$sql='SELECT id, position, platoon, name, status FROM ost_platoon_assignments';
$users=db_query($sql);
$num=db_num_rows($users);
while ($row = db_fetch_array($users)) {
$info = array(
$row['position'] => array(
$row['platoon'] => array("name" =>$row['name'], "status" => $row['status']),
),
);
}
I want to list via a table by those in a particular position:
example:
<table border="1">
<?
foreach ($info as $position => $names) {
echo "<tr>";
echo "<td> {$position} </td>";
foreach ($names as $name) {
if ($name[name] =="") {$name[name] = "Vacant"; }
echo "<td class=\"status{$name[status]}\"> {$name[name]} </td>";
}
echo "</tr>";
}
?>
</table>
What am I missing? When I run this it only gives me the last entry.
Thanks for your help
You are overwriting the value of $info with each iteration of your while statement.
If you want to store all your data in array structure like this:
$info = array(
'general' => array(
array( /* general 1 */ ),
array( /* general 2 */ ),
array( /* general 3 */ )
),
'colonel' => array(
array( /* colonel 1 */ ),
array( /* colonel 2 */ ),
),
// .....
)
Then use a process like the following: (Note I'm using PDO, you could also use PHP'S mysqli, but use one of these instead of PHP's mysql library which is deprecated).
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$result = $conn->query('SELECT id, position, platoon, name, status FROM ost_platoon_assignments');
$info = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$info[$row['position']][] = $row;
}
You can then loop through each user by position like this
foreach ($info as $position => $users) {
foreach ($users as $user) {
// ....
}
}
It should be
$info[] = array( ..... );
^^-----
instead. Right now you're continually OVERWRITING $info with every result row being retrieved. The [] notation will PUSH the new row onto the $info array, instead of simply replacing what was there previously.

Categories