Grab DB values and display For Each - Codeigniter - php

Having a bit of trouble getting my For Each function to display all the values from a DB into a view. Where am I going wrong? Not a back-end pro, nor did I write it. Database table is extremely simple, one column named id. I want to display each of the rows in my for each.
I have a custom MY_Controller.php file and in the _construct I have this, which fills in variables globally across the site.
$this->country_zones = $this->Studios_model->get_studios();
Model:
function get_studios()
{
//this will alphabetize them
$this->db->order_by('id', 'ASC');
$query = $this->db->get('gc_studio_zones');
foreach ($query->result() as $row)
{
$countries = $row->id;
}
return $countries;
}
In my view:
<?php foreach($this->$country_zones as $country):?>
<li><?php echo $country['countries']->id;?></li>
<?php endforeach;?>
Error:
Cannot access empty property...etc

I think you have a typo in your view regarding your loop variable, it should be this->country_zones:
<?php foreach($this->country_zones as $country):?>
<li><?php echo $country->id;?></a></li>
<?php endforeach;?>
Besides, your Model isn't returning an array, but only the last id. You need to push the values to your result array:
function get_studios()
{
//this will alphabetize them
$this->db->order_by('id', 'ASC');
$query = $this->db->get('gc_studio_zones');
$countries = array();
foreach ($query->result() as $row) {
$countries[] = $row;
}
return $countries;
}

Related

How to output codeigniter selects_sum in the view without foreach

How can I output the result of select_sum from controller to the view without using foreach. I don't want to use foreach because my function returns only 1 number.
The logic is I have a column in DB with numeric values called 'time', I want to sum all of them together, and output the result next to /10000 in my view.
I believe I need to use row() but I am not sure how.
Controller:
$this->load->library(array('form_validation', 'session'));
$this->db->select_sum('time');
$data['num'] = $this->db->get('posts');
$this->db->order_by('id', 'DESC');
$data['query'] = $this->db->get('posts');
$this->load->view('templates/header');
$this->load->view('templates/navigation');
$this->load->view('home_page', $data);
$this->load->view('templates/footer');
View:
<?php foreach ($num->result() as $row): ?>
<?php if (empty($row->time)): echo "0"?>
<?php else: echo $row->time ?>
<?php endif ?>/10000</p>
<?php endforeach;?>
You can combine row() with the variable.
$sql = $this->db->select_sum('time');
$sql = $this->db->get('posts');
$data['num'] = $sql->row();
And you can call in your view
$num->time;
hope this solve your problem.

Invalid argument supplied for foreach() due to var_dump is null

Yesterday when I var_dump($this->m_test->result_getGrades());it gave me an array[1356] now it returned null. Can anyone help me figure out why it's NULL? I'm still new in PHP and Codeigniter and its pretty stressful figuring out why I can't retrieve any data from my database.
I assume the reason why I have this error because ($this->m_test->result_getGrades()) is NULL
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/v_display.php
Line Number: 7
Also, What are the factors why I can't retrieve any data from my database? For future references
This is my code:
Controller c_test.php
function getGrades() {
$data['query'] = $this->m_test->result_getGrades();
$this->load->view('v_display', $data);
}
Model m_test.php
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode=subject.subjectcode');
$this->db->where('2013-F019');
$query=$this->db->get();
}
Views v_display.php
<?php foreach ($query as $row): ?>
<?php echo $row->studentid;?><br>
<?php echo $row->subjectcode;?><br>
<?php echo $row->description;?><br>
<?php echo $row->final;?><br>
<?php endforeach; ?>
Thank you once again! :)
You should try this:
First, you will need to check your where clause.
see example below:
$this->db->where('name', 'test');
that will produce WHERE name = 'test' in the MySQL query
then you have to put a return statement after your get() method:
$query = $this->db->get();
return $query->result_array();
so your model should be something like this:
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode=subject.subjectcode');
$this->db->where('name of field', '2013-F019');
$query=$this->db->get();
return $query->result_array();
}
There are many faults in your result_getGrades() function :
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode = subjects.subjectcode');
$this->db->where('your_field', '2013-F019');
$query = $this->db->get()->result();
return $query;
}
There was :
add the return $query;
field name in your where clauses
subject to subjects in your join
var dumping the query itself usually doesn't return much for me usually but it depends on when you dump it.
<?php foreach ($query as $row): ?>
<?php echo $row->studentid;?><br>
<?php echo $row->subjectcode;?><br>
<?php echo $row->description;?><br>
<?php echo $row->final;?><br>
<?php endforeach; ?>
For this you don't need to keep opening and closing the php tags unless you want alot of html around it:
<?php foreach ($query as $row){
echo $row->studentid.'<br>';
echo $row->subjectcode.'<br>';
echo $row->description.'<br>';
echo $row->final.'<br>';
}?>
Notice the . ? It joins the $row->studentid to the html meaning it's alot cleaner code.
Now onto the question, you're assigning a variable as a variable in your foreach...Which is pointless. Thankfully i know the fix. You need to turn the query into a result from your database:
<?php foreach ($query->result() as $row){
echo $row->studentid.'<br>';
echo $row->subjectcode.'<br>';
echo $row->description.'<br>';
echo $row->final.'<br>';
}?>
$query->result() as $row will enable you to echo out the information you get back from the database.
Also at the end of the model, you need to add return $query; otherwise your model is getting the data and not doing anything with it.

Return n value of array Function and list in while loop PHP

I'm trying to show list of countries by the use of PHP function.
Here's the database value that I'm retrieving on. (cropped)
Here's the function that I'm retrieving the data.
Code:
public function get_countries() {
$list_country = array();
$query = $this->db->prepare("SELECT name FROM country");
$query->execute();
while($r = $query->fetch(PDO::FETCH_ASSOC)) {
$list_country[] = $r['name'];
}
return $list_country;
}
Then here's the code where I echo all the data.
<?php
while (list($country) = $general->get_countries()) {
echo $country;
}
?>
Unfortunately, it just all echo the same value over and over again.
Any solution for this? Like echo-ing all the data instead of the same data over and over again?
<?php
$country_array = $general->get_countries();
foreach ($country_array as $country) {
echo $country;
}
?>
You don't need the while() as you already fetched all countries with get_countries() function. Moreover, with list() you retrieve only the n array elements where n is the number of variables inside list() function.
So, why are you getting every time the same value?
Because you're calling every time a db function for read country content and every time you're retrieving the same value (the first)
$query = $PDO->prepare("SELECT blah FROM table");
$country = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$country[] = $row['blah'];
}
That code worked for me. You can set some exception if the query returns null this would suppress your warnings in the while loop.
Hope that helps

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';
}

Subarray within foreach loop php

I have this code here:
<?php foreach($blog_posts['post_category'] as $category) { ?>
How can I get this to work?
Basically I have a database with all my blog posts within them, one of the columns is post_category I'm trying to make a list out of all these by a foreach statement that gets the results like so:
$data['blog_categories'] = $this->db->query("SELECT `post_category` FROM `blog_posts`");
This is codeigniter by the way... Then in my view I have the code:
<?php foreach($blog_posts['post_category'] as $category) { ?>
I need to display each category in an li...
You wanna use implode I think
$output = array();
forreach($blog_posts['post_category'] as $item){
$output[] = "<li>$item</li>";
}
echo "<ul>".implode('',$output)."</ul>";
Or if you were just after the list items and not list just replace the last line with
echo implode('',$output);
Pretty sure what you're looking for is
$data['blog_categories'] = $this->db->query("SELECT DISTINCT `post_category` FROM `blog_posts`");
foreach ($data['blog_categories'] as $category) {
echo "<li>$category</li>";
}
Me, I'd change $data['blog_categories'] to just $blog_categories or something, but I kept it as you had it so as not to confuse the issue.

Categories