For each inside other for each on view MVC PHP - php

I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help

This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>

Related

Display data from database PHP OOP

I'm pretty new to PHP OOP and i have to make a small web app for school.
One of the things i'm trying to do right is to select data from the database and display it in my front-end. I figured out how to display a single row but i wanted to display all rows in the table. How can i do that?
My function:
public function listJobs(){
$myDb = $this->_controlPanel->getMyDb();
$query = "Select * FROM jobs_offers";
$result = $myDb->performQuery($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$this->title=$row['title'];
$this->description=$row['description'];
$this->category=$row['category'];
$this->budget=$row['budget'];
}
My front-end:
<?php
header ('Content_type: text/html; charset=ISO-8859-1');
require_once ('utils/Autoloader.php');
session_start();
if (empty($myControlPanel)) {
try {
$myControlPanel = new classes_ControlPanel();
$myControlPanel->setMyDb(new classes_DbManager());
$myDbManager = $myControlPanel->getMyDb();
}
catch (Exception $e) {
echo $e->getMessage();
die();
}
}
$log = new classes_UserManager($myControlPanel);
$select = $log->listJobs();
$title = $log->title;
$description = $log->description;
$category = $log->category;
$budget = $log->budget;
?>
<body>
<div class="container-fluid">
<h2>
<h2><?php echo $title; ?> </h2>
<h2><?php echo $description; ?> </h2>
<h2><?php echo $category; ?> </h2>
<h2><?php echo $budget; ?> </h2>
</div>
First, the result will return an array of objects (PDO). You would want to return this array to your view. Or, in your case as a property of the object and not the single row like you did above.
Next, You want to use a foreach or while loop in the view. If you are using PDO (Php Data Object) you can do the following.
while($job = $result->fetch_assoc()) {
{
?>
<div class="container-fluid">
<h2>
<h2><?= $job->title; ?> </h2>
<h2><?= $job->description; ?> </h2>
<h2><?= $job->category; ?> </h2>
<h2><?= $job->budget; ?> </h2>
</div>
<?php
}
(Short Tags (<?=$var?>) are equivalent to <?php echo $var?>)
Reference: http://www.w3schools.com/php/php_mysql_select.asp

PHP Error: Trying to get property of non-object

I am working in CodeIgniter framework and I have tried to apply all the other solutions I found on stack but I could not make it work so here is my problem...
I am trying to retrieve a record from MySQL database table called 'questions' based on uri segment. Then I am trying to display this record in a view. As far as I can tell, the uri segment is passed along everywhere it needs to be, and record is retrieved from database.
The problem comes up when I am trying to access the data from the controller, in my view.
Error I am getting for each echo in my loop in 'view_thread_view' is
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_thread_view.php
Any solutions would be greatly appreciated.
Here is my code:
Controller thread
function view_thread()
{
$quest = $this->uri->segment(3);
echo $quest;// for checking if uri segment is passed
if($query = $this->data_model->get_thread($quest))
{
$data['records'] = $query;
}
$this->load->view('view_thread_view', $data);
Model data_model
public function get_thread($quest)
{
if($q = $this->db->get_where('questions' , 'qid' , $quest));
{
return $q;
}
}
View view_thread_view
<div title="question_view">
<h1>Question View<h1>
<?php foreach($records as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $records->uname
?>
</div>
<?php endforeach; ?>
</div>
EDIT: QUESTION ANSWERED
Thanks to Girish Jangid fixed the problem this is the working code:
Controller
function view_thread()
{
$quest = $this->uri->segment(3);
echo $quest;// for checking if uri segment is passed
//$data = array();
if($query = $this->data_model->get_thread($quest))
{
$data['records'] = $query;
}
$this->load->view('view_thread_view', $data);
}
Model
public function get_thread($quest)
{
if($q = $this->db->get_where('questions' , array('qid' => $quest)));
{
return $q;
}
}
View
<div title="question_view">
<h1>Question View<h1>
<?php foreach($records->result() as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $data->uname
?>
</div>
<?php endforeach; ?>
</div>
</div>
You should user db function to fetch results, please use CodeIgniter db Query Results functions, like this
if($records->num_rows() > 0){
foreach($records->result() as $data){
if(isset($data->title)) echo $data->title;
}
}
For more detail please read CodeIgniter Query Result function
Query Results
Try this code
<div title="question_view">
<h1>Question View<h1>
<?php if($records->num_rows() > 0) { ?>
<?php foreach($records->result() as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $records->uname
?>
</div>
<?php endforeach; ?>
<?php } ?>
</div>
$records is an array, not an object, therefore you cannot do $records->uname. You probably meant $data there too.
Edit: On second look, it appears $data is an array as well! Arrays are accessed via ['key'] not ->key
Also, your code is way over complicated.
<?php
foreach($records as $data){
$string = <<<STR
<div>
<h2>Title</h2>
{$data['title']}
</div>
...etc
STR;
echo $string;
}
http://www.php.net/manual/en/language.types.string.php

Tabular Input Yii

I have to input several strings into table in db. Its tabular input yii. Cannot understand, how to do it this way, if i have such controller:
public function actionCreate()
{
$model1=new Section;
$model2=new SectionI18n;
if(isset($_POST['SectionI18n'])){
foreach ($model2 as $i => $m1) {
foreach($_POST['SectionI18n'] as $i => $m1)
{
$m1=new SectionI18n;
$m1->attributes=$_POST['SectionI18n'][$i];
$my[]=$m1->attributes;
}
}
and some layout:
<?php foreach ($model2 as $i=>$m1):?>
<?php ?>
<div class="row">
<?php echo $form->labelEx($model2,'Название'); ?>
<?php echo $form->textField($model2,'[$i]title',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model2,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model2,'Описание'); ?>
<?php echo $form->textArea($model2,'[$i]description',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model2,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model2,'Язык'); ?>
<?php echo $form->dropDownList($model2,'[$i]lang',array('ru'=>'ru','en'=>'en','ua'=>'ua')); ?>
<?php echo $form->error($model2,'lang'); ?>
</div>
<?php ?>
<?php endforeach;?>
Help please
It would be something similar to this:
foreach ( $_POST[Model Name] as $i => $y ){
$var name[$i] = new Model Name;
$var name[$i]->title = $_POST[Model Name][$i][title]
...
}
var_dump the post ($_POST), object makes it easier to see.

Error message keeps coming back saying the array is not defined.

I'm developing a website using Codeigniter. The structure site is simple, I have dynamic menu and content retrieving DB in Model. Then assign a method to call both of them in Controller.
I have that weird error message keeps coming back saying the array is not defined.
I can get tabPhotos, it contains datas.
View:
<div id="container">
<div id="photos">
<?php echo "Count: ". count($tabPhotos); ?>
<ul>
<?php if (!is_array($tabPhotos) || empty($tabPhotos)) :?>
<?php return null; ?>
<?php foreach ($tabPhotos as $item) : ?>
<?php echo "Model: " . $item->url; ?>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
</div>
Controller:
public function loadMenu($file) {
$data['tabMenuItems'] = $this->qdphoto_model->getAllMenuItems();
$this->load->view($file, $data);
}
public function loadCategoryPage($file, $category='Book 1') {
$data['tabPhotos'] = $this->qdphoto_model->getAllPicturesByCategory($category, 'url, model');
$this->load->view($file, $data);
}
Am I reading this correctly? if $tabPhotos IS NOT an array OR it is and it happens to be EMPTY then return null and continue to run the foreach loop with a mysterious endif following?
<?php if (!is_array($tabPhotos) || empty($tabPhotos)) :?>
<?php return null; ?>
<?php foreach ($tabPhotos as $item) : ?>
<?php echo "Model: " . $item->url; ?>
<?php endforeach; ?>
<?php endif; ?>
Shouldn't it read this:
<?php if (is_array($tabPhotos) && !empty($tabPhotos)) :?>
<?php foreach ($tabPhotos as $item) : ?>
<?php echo "Model: " . $item->url; ?>
<?php endforeach; ?>
<?php endif; ?>
no need for that return null statement.
Also, I believe you can return views as strings. If you want to load more than one view you can certainly load any fragment of your view as a string...
$string = $this->load->view($file, $data, true);
Please note that you should review this:
http://codeigniter.com/user_guide/general/views.html
See bottom. It says how to return as string, except that I am used to slightly different syntax thanks to custom controllers and such. Perhaps this example I provided is not accurate.

PHP - limiting the output of a plugin

I'm using a plugin titled "WP Recent Links" which I first learned about via Eric Meyer's site. Eric uses to display a Link Log within his site and I'm doing the same on my test site - http://matala.jorgeledesma.net/ but I'm running into a little situation and that is that I don't know how to limit the output either on the sidebar or the actual page - http://matala.jorgeledesma.net/recent-links/
My goal is to have it echo only the first 5 entries on the sidebar and for the recent-links page only echo the current month. The code below displays the sidebar properly
<?php if (!is_page('48')) { ?>
<aside id="meta" class="widget">
<h1 class="widget-title">Link Log</h1>
<?php if ($links = rp_recentlinks_home()) { ?>
<ul>
<?php foreach ($links as $link) { ?>
<b><li><?php echo wptexturize($link->link_text); ?></b>
<?php if ('' != $link->link_caption) { ?>→
<?php echo wptexturize(convert_smilies($link->link_caption)); ?><?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
</aside>
<?php } ?>
and this code display the actual recent-links page
<h1 class="page-title"><?php rp_recentlinks_archive_header(); ?></h1>
</header>
<div class="entry-content">
<?php $links = rp_recentlinks_archive_page(); ?>
</div>
<?php if ($links) { ?>
<ul>
<?php foreach ($links as $link) { ?>
<p id="rlink-<?php echo $link->ID; ?>"><?php echo wptexturize($link->link_text); ?>
<?php if ('' != $link->link_caption) { ?>→
<?php echo wptexturize(convert_smilies($link->link_caption)); ?><?php } ?>
</p>
<?php } ?>
</ul>
<?php } ?>
I tried putting the following code in the body.
$list = array_slice($input, 0, 5); // $list now only having first 5 item.
But I don't know how to apply it, if that's the command at all. So perhaps, someone can guide in the right direction. Thanks in advance, Jorge.
Looks like all you have to add is this before you pass $links to the foreach loop:
$links = array_slice($links,0,5);

Categories