Print a row of database by foreach - php

I use codeigniter. I want print rows name of database by foreach. is not array value row name in the database.
My way don't work and is output: Array
In the Controller:
$query = $this->db->query("SELECT * FROM welcome ORDER BY id desc");
$data = array();
foreach ($query->result() as $row)
{
$data['output'] = array('name' => $row->name);
}
$data['output'] = $data;
$this -> load -> view('welcome', $data);
In the view:
<?=$output?>

I put as your example, but queries should be in model:
$query = $this->db->query("SELECT * FROM welcome ORDER BY id desc");
$data = array();
foreach ($query->result() as $row){
$data['output'][] = $row->name;
}
$this -> load -> view('welcome', $data);
In the view:
<pre>
<?=print_r($output)?>

$output is an array of values, so to print it out, you need to use a function such as print_r().
<?php
print_r($output);
?>
Using echo or the PHP short output tags on an array will output the data type Array instead of it's contents.

You should not use <?=$output?> to see arrays.
Arrays are structured variables that are composed of multiple keys and values.
That way you should use either:
print_r() - http://php.net/manual/en/function.print-r.php
or
var_dump() - http://php.net/manual/en/function.var-dump.php

if you want to print your array, display it all with this:
foreach ($output as $stuff) {
print_r($stuff);
/* and a break like */
/* in care your array is multidimensional */
}

Related

PHP function foreach/while loop save multiple or array of values

I have this code which I want to save all of the column values taken from Mysql database.
<?php
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
$data=$db->query("select * from item");
foreach($data as $k=>$v){
return $v['item_name'];
}
}
echo itemName($db); //output:item1
?>
The problem is above code only returned the first row of data. Although I can use echo inside of the foreach loop like "echo $v['item_name'];", then call the function which will output all the values like item1 item2 item2 etc. My question is how can I use return to save all off the values equivalent like echo does, but not immediately echoed out.
Collect data in array and return this array from your function:
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
$data=$db->query("select * from item");
$result = [];
foreach($data as $v){
$result[] = $v['item_name'];
}
return $result;
}
print_r(itemName($db));

When I try to access to array items I only get the 1. one

Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.

Fetching data from mysql table and placing values inside a JSONObject

I am fetching values from mysql table. I am then placing the values inside an array and using th php built function json_enconde to convert these values into a json format. I am getting results back but not in the desired format. In the php code you will notice I am using array and fetching values with a foreach loop to place all values inside. As a result I am getting back several json objects. How can I get back just one json object with the corresponding values?
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[] = array(
$row["id"] => $row["name"]
);
} // foreach ($data as $row) {
echo json_encode($json_data);
Results:
{
1: "Item1"
},
{
2: "Item2"
},
{
3: "Item3"
}
Desired Results:
{
"1":"Item1",
"2":"Item2",
"3":"Item3"
}
change this array( $row["id"] => $row["name"]);
to $json_data[$row["id"] ] = $row["name"] inside the for loop
foreach ($data as $row) {
$json_data[$row["id"] ] = $row["name"];
}
try this
foreach ($data as $row) {
$id=$row["id"];
$json_data[$id] =$row["name"];
}
The problem was that while defining the value in json_data in your foreach loop you are creating an array for every single value, so you are not getting the desired result.
You will need to change your PHP code to create a normal single dimensional array, right now you are creating a multidimensional array. Your PHP should be like this:
header("Content-type: application/json");
$query = $db_con->prepare("SELECT id, name FROM table");
$query->execute();
$data = $course_query->fetchAll();
$json_data = array();
foreach ($data as $row) {
$json_data[$row["id"]] = $row["name"];
} // foreach ($data as $row) {
echo json_encode($json_data);
Notice the change in the foreach loop, we are no longer appending a new array onto the $json_data array(which would create a multidimensional array). This will give you a single dimensional array with the proper key:value pairs. Then when you run the json_encode you will get your desired JSON format.

Selecting records from a database table in PHP using CodeIgniter and pass to a view

I'm making a query in PHP using CodeIgniter to get the data that I wanted from a database. To be able to get all values for a specific column, I stored it into an array and passed it into a view. But I can do it only for one column.
Here's my code:
$query = $this->db->query('SELECT name, description FROM module');
$result = $query->result_array();
foreach ($result as $key => $rowdata) {
$resultdata['values'][$key] = $rowdata['name'];
}
$this->load->view('myview', $resultdata);
With this scenario I can get all name from the module table. But my problem is, I also wanted to get all the description in the module table, but I don't know how can I implement it and be able to pass it into the view. Hope someone could help me with this. Thanks!
Your not using the MVC pattern!
First you should write your query in a model!
Then load it in your controller like this
$this->load->model('ModelName');
Then call the funcion to retreive the data
$data = $this->modelname->functionToRetreiveData();
Then loop through data with foreach
$dataToView = array();
foreach($data as $key=>$row)
{
$dataToView['something'][$key]['value'] = $row->name_of_column;
}
And pass the array to the view $this->load->view('someview',$dataToView);
Then in the view
foreach($value as $val):
<p><?php echo $val['name']?><p>
endforeach
hi in you way you will do loop twice in controller and then in view to print it check this out
//in controller
$query = $this->db->query('SELECT name,description FROM module');
$resultdata['results'] = $query->result_array();
$this->load->view('myview',$resultdata);
myview.php
foreach($results as $result)
{
echo $result['name'],' ',$result['description'];
}
$query = $this->db->query('SELECT name,description FROM module');
$result = $query->result_array();
foreach($result as $rowdata){
$resultdata['values'][] = $rowdata;
}
$this->load->view('myview',$resultdata);
Try in view:
print_r($values);
You will probably have:
$result[0]['name'], $result[0]['description'] ...
$this->load->database();
$this->db->select('employee');
$query = $this->db->get();
return $query;
foreach ($query as $row) {
print $row->'Name';
.
.
.
print $row->'Address';
}

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