What my code does:
I am returning arraylist from a php method -->method name:- getSubjectInfo().
And in my (Index.php) page i am getting this arraylist values in a $results variable. Here i am stuck how to iterate the arraylist values in the index.php page?.
My Problem: How to iterate the arraylist ($results) in my index.php page? Please see my below mention code
i have used $results = $sub_info->fetchAll(PDO::FETCH_OBJ); in my method for generating list.
index.php
<?php
include_once '../../classes/conn/connection.php';
include_once '../../classes/setups/Subdetails_setup.php';
$con = new connection();
$info = new Subdetails_setup($con);
$results = $info->getSubjectInfo();
echo $results; //this is returning a list of objects. My problem is how can i iterate these values
?>
and i tried like this echo (each($results)); but this is printing my values in a single line
like this:- Subject Name 1 FIction1Non FIction2
& My Subdetails_setup.php Class is having method getSubjectInfo() :-
function getSubjectInfo()
{
$sub_info = $this->con->prepare("SELECT * FROM subjectdetails");
$sub_info->execute();
$results = $sub_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
// Return the result array
return $results;
}
Please help me for this.
-Ashutosh
This code in your Subdetails_setup.php needs to be removed, and put on the index.php. You don't need it in subdetails, just return the result.
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
If you want to check if it's all working, change your index.php and add this line:
$results = $info->getSubjectInfo();
var_dump($results);
Now that var_dump() works, replace the line with the earlier code, modified to show a table:
foreach ($results as $key)
{
echo "<tr>";
echo "<td>".$key->subject_name."</td>";
echo "<td>"$key->subject_id."</td>";
echo "</tr>";
}
Related
so i am learning to write functions. Now i know how to echo stuff into a foreach but i do not know how to print a single row outside a foreach (like i only have 1 row in my table and want to print the id and username out of it) how do i do this?
my function :
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
when i call that function on my other page i call it with :
require_once 'class/class.overig.php';
$overig = new OVERIG();
i have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?
Because you are using ->fetchAll() you will always get an array of rows even if there is only one row returned. You also need to use the correct method name on your call.
So all you need to do is
$arr = $overig->gegevens();
if ( count($arr) == 1 ) {
echo $arr[0]['id'];
echo $arr[0]['username'];
}
if ( count($arr) > 1 ) {
foreach ( $arr as $row) {
echo $row['id'];
echo $row['username'];
}
}
"I have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?"
The Name of the Method you called does NOT match the Name of the Method in your Class. In your Class, You have: gegevens() but in your Call: you specified: gevens(). Unless this is just a normal Typo; you should start your Debugging from there.
In other words; your Call should have been: print_r($overig->gegevens()).
THE CLASS:
<?php
class OVERIG{
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
}
USING THE CLASS:
<?php
require_once 'class/class.overig.php';
$overig = new OVERIG();
$result = $overig->gegevens();
// TRY DUMPING THE VARIABLE: $result:
var_dump($result);
// TO ECHO OUT SOME VALUES:
if($result){
foreach($result as $key=>$item){
if(is_string($item)){
echo $item;
}
}
}
Let's think that we have a db and a model function that retrieve a query result like this:
public function lista_ordini ($idcliente)
{
$this->db->select('ordini.num_fattura, misure.cosplay, ordini.data_richiesta,
ordini.anticipo, ordini.data_consegna,
ordini.saldo_totale, ordini.stato');
$this->db->join('misure', "ordini.id_cliente = $idcliente");
$query = $this->db->get('ordini');
if ($query && $query->num_rows() > 0){
return $query;
}else{
echo "errore generazione query ordini";
}
}
}//This is missing in your original, I'm not sure if it's a typo
Using codeigniter's table helper to generate a table:
<?php echo $this->table->generate($query); ?>
I can generate the table...and this is ok and works...
but, What if I want that every rows has a specific field (or the entire row if it's simpler) with href link? (this link will pass thorough GET method a variable for generate another query, but I don't figure out yet how that will work, this is just an hobby project)
I try this:
public function lista_ordini ($idcliente)
{
$this->db->select('ordini.num_fattura, misure.cosplay, ordini.data_richiesta,
ordini.anticipo, ordini.data_consegna, ordini.saldo_totale,
ordini.stato');
$this->db->join('misure', "ordini.id_cliente = $idcliente");
$query = $this->db->get('ordini');
if ($query && $query->num_rows() > 0) {
$rows = $query->row();
foreach ($rows as &$row) {
$row['num_fattura'] = ''.$row['num_fattura'].'';
}
return $rows;
}else{
echo "errore generazione query ordini";
}
}
I'm pretty sure that foreach loop is the way, but I can't understand how, cause I have so much errors that I cannot understand...to make this simply, my code doesn't work, and I think that I need some semantic advice.
thank you in advace
There is a logical problem in the foreach loop here:
foreach ($rows as &$row) {
$row['num_fattura'] = ''.$row['num_fattura'].'';
}
return $rows;
Each time the loop runs you are changing the value of $row, but when it completes you are returning $rows, which is unchanged.
Instead, you could edit the original array, using $k => $v to access the key and value inside the foreach loop:
foreach ($rows as $k => $v) {
$rows[$k]['num_fattura'] = ''.$rows[$k]['num_fattura'].'';
}
return $rows;
I know what you're trying to do, but I dont understand how you are trying to do it. Here's How I would do it:
//controller method
public function show_data()
{
$this->load->library('table');
$data['table_data'] = $this->some_model->get_the_data();
$this->load->view('some_view_that_will_contain_my_table', $data);
}
Now in my view, I'd generate the table:
<!doctype html>
...
<?if(!empty($table_data)):?>
<? $this->table->set_heading('column_1', 'column_2');?>
<?foreach($able_data as $table_row):
$this->table->add_row(
array('data'=>''.$table_row['column_1'].'.'),
array('data'=>''.$table_row['column_2'].'.'),
);
endforeach;?>
<?= $this->table->generate();?>
<?endif;?> //or display an empty table
I tried the following code for selecting all the records from mongodb collection.But only last inserted record will come.
<?php
$m=new MongoClient();
$db=$m->trip;
if($_SERVER['REQUEST_METHOD']=="POST")
{
$userId=$_POST['userId'];
$param=explode(",",$userId);
$collection=$db->chat;
$record=$collection->find(array("userId"=>$userId));
if($record)
{
foreach($record as $rec)
{
$json=array("msg"=>$rec);
}
}
else
{
$json=array("msg"=>"No Records");
}
}
else
{
$json=array("msg"=>"Request Method is Not Accespted");
}
//output header
header('Content-type:application/json');
echo json_encode($json);
?>
But only one record will come
please help me
Your problem is that each time your foreach executes, it overrides the content of $json variable. Try declaring $json first and then using it.
if($record)
{
$json = array();
foreach($record as $rec)
{
$json[] = array("msg"=>$rec);
// /\ this means adding the attribution to the end of the array.
}
}
This way, each time the foreach is executed, the content of $json won't be replaced, instead it will be appended.
I want to pass the array of values fetched from the database as a parameter to a php function.If I echo the value, it doesn't display it.
<?php
include "config.php";
$sql="select * from project where comp_id='1'";
$sql1=mysql_query($sql);
$rows=array();
while( $fet=mysql_fetch_array($sql1))
{
$rows[]=$fet;
}
echo fun_parameter($rows);
function fun_parameter($rows)
{
echo" rows". $rows['start_date']."values"; // not working
}
foreach($rows as $row)
{
echo $name=$row['start_date']; /working
}
?>
Simple looping can give the result,
function fun_parameter($rows)
{
foreach($rows as $row)
{
echo $row['p_id']; /working
echo" rows". $row['start_date']."values";
}
//echo" rows". $rows['start_date']."values"; // not working
}
If you want to fetch particular column from multi dimensional array then take a look into array_column() in php
in your code you are trying to echo an array $row without its index specified, you need to loop through that array as it has got mulitple value, use the following code:
<?php
include "config.php";
$sql="select * from project where comp_id='1'";
$sql1=mysql_query($sql);
$rows=array();
while( $fet=mysql_fetch_array($sql1))
{
$rows[$i]['start_date']=$fet['start_date'];
}
echo fun_parameter($rows);
function fun_parameter($rows)
{
foreach($rows as $row)
{
echo" rows". $row['start_date']."values"; // use loop it will work
}
}
foreach($rows as $row)
{
echo $name=$row['start_date']; // i left this foreach here because you had it in your code
}
I can't retrieve values from $info (as stated below) in CodeIgniter View.
Here is the scenario:
I explained everything the code.
function info() {
{...} //I retrieve results from database after sending $uid to model.
$dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value.
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$results = $this->my_model->show_info($info);
return $results; //This is my final result which can't be achieved without using $row->address. so first I have to call this in my controller.
}
// Now I want to pass it to a view
$data['info'] = $results;
$this->load->view('my_view', $data);
//In my_view, $info contains many values inherited from $results which I need to call one by one by using foreach. But I can't use $info with foreach because it is an Invalid Parameter as it says in an error.
using $result inside foreach is not reasonable. Because in each loop $result will take a new value. So, preferably use it as an array and then pass it to your view. Besides, you should not use return inside foreach.
function info() {
{...} //I retrieve results from database after sending $uid to model.
$dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value
$result = array();
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$result[] = $this->my_model->show_info($info);
}
// Now I want to pass it to a view
$data['info'] = $result;
$this->load->view('my_view', $data);
}
to check what $result array has do var_export($result); or var_dump($result); after the end of foreach. and make sure that this is what you want to send to your view.
Now, in your view you can do:
<?php foreach ($info as $something):?>
//process
<?php endforeach;?>
Please remove return statement from
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$results[] = $this->my_model->show_info($info);
// return $results; remove this line from here;
}
$data['info'] = $results; // now in view access by $info in foreach
$this->load->view('my_view', $data);
now $info can be access in view.
hope this will help you!