I have the following function.php:
function getPublishedPosts() {
// use global $conn object in function
global $conn;
$sql = "SELECT * FROM posts WHERE published=true";
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
$final_posts = array();
foreach ($posts as $post) {
$post['topic'] = getPostTopic($post['id']);
array_push($final_posts, $post);
}
return $final_posts;
}
and I am calling it to the other page with this:
<!-- THIS LOOP -->
<?php $posts = **getPublishedPosts();** ?>
<div class="content">
<h2 class="content-title">Recent Articles</h2>
<hr>
<!-- more content still to come here ... -->
<!-- Add this ... -->
<?php $posts = getPublishedPosts(); ?>
<?php foreach ($posts as $post): ?>
<div class="post" style="margin-left: 0px;">
<img src="<?php echo BASE_URL . '/static/images/' . $post['image']; ?>" class="post_image" alt="">
<!-- Added this if statement... -->
<?php if (isset($post['topic']['name'])): ?>
<a
href="<?php echo BASE_URL . 'filtered_posts.php?topic=' . $post['topic']['id'] ?>"
class="btn category">
<?php echo $post['topic']['name'] ?>
</a>
<?php endif ?>
<a href="single_post.php?post-slug=<?php echo $post['slug']; ?>">
<div class="post_info">
<h3><?php echo $post['title'] ?></h3>
<div class="info">
<span><?php echo date("F j, Y ", strtotime($post["created_at"])); ?></span>
<span class="read_more">Read more...</span>
</div>
</div>
</a>
</div>
<?php endforeach ?>
</div>
However, when it is on the server, the page goes blank.
I finally solved it, it was just a server extension and version problem regarding the incompatibility of my function.
Normally when I get the data from my database I there are arranged in the order of their id.However, I have created a column called 'sales' which is also an integer
and I would like my data to be arranged in ascending order according to the sales.Here is my code:
My Model
public function get_bestseller($id = FALSE) {
if ($id === FALSE)
{
$query = $this->db->get('submit');
return $query->result_array();
}
$query = $this->db->get_where('submit', array('id' => $id));
$this->db->order_by('sales', 'DESC');
return $query->result_array();
}
My View
<div class="tab-pane fade" id="faq-cat-2">
<div class="panel-group" id="accordion-cat-2">
<?php foreach ($bestseller as $bestseller_item): ?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img class="lazy" src="<?php echo base_url() ?>Images/last.gif"
data-original="<?php echo base_url() ?>uploads/<?php echo $bestseller_item['imgname']; ?>"
style="width: 350px; height: 150px">
<div class="caption">
<?php if ($bestseller_item['Price'] == 0): ?>
<h4 class="pull-right"><p class="text-success">Free</p></h4>
<?php else: ?>
<h4 class="pull-right">$<?php echo $bestseller_item['Price']; ?></h4>
<?php endif; ?>
<h4>
<a href="<?php echo site_url('submit/view/' . $bestseller_item['id']); ?>"
target="_blank"><?php echo $bestseller_item['Title']; ?></a>
</h4>
<p><?php echo $bestseller_item['textarea']; ?></p>
</div>
<p class="text-right"><b
class="author">By: <?php echo $bestseller_item['Author']; ?></b>
</p>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
My Controller
public function index()
{
$data['bestseller'] = $this->Submit_Database->get_bestseller();
$this->load->view('templates/header');
$this->load->view('pages/home', $data);
$this->load->view('templates/footer');
}
$query = $this->db->order_by('sales', 'DESC')->get_where('submit', array('id' => $id));
You are adding the order by clause after the query has already ran.
I have for each loop return an array
<?php foreach( get_uf_repeater( 'clients' ) as $document_files ): extract( $document_files ) ?>
<div class="ui-grid-a my-breakpoint">
<div class="ui-block-a"><img src="<?php echo $project_image ?>" title="Project image" /><div><?php echo $project_detailes ?></div></div>
<div class="ui-block-b"><img src="<?php echo $project_image ?>" title="Project image" /><div><?php echo $project_detailes ?></div></div>
</div>
<?php endforeach ?>
how can i jump to the next array for the second line "" instead of displaying the same of the first one, I assume I need nested loop but didnt know how do it exactly.
You could use array_chunk
<?php foreach (array_chunk(get_uf_repeater( 'clients' ), 2, true) as $array) { ?>
<div class="ui-grid-a my-breakpoint">
<?php foreach($array as $document_files) { ?>
<?php extract( $document_files ); ?>
<div class="ui-block-a"><img src="<?php echo $project_image ?>" title="Project image" /><div><?php echo $project_detailes ?></div></div>
<?php } ?>
</div>
<?php } ?>
My controller code just generate ten copies of the same data. And I put the data in an array of array.Controller Code Below:
for($i=0;$i < $this->per_page;$i++)
{
$temp['title'] = "test";
$temp['link'] = "localhost/cib/index.php";
$temp['month'] = '4';
$temp['day'] = '21';
$temp['authorlink'] = "localhost/cib/index.php/author";
$temp['author'] = "Charles";
$temp['content'] = "tetestersafaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
$results[] = $temp;
}
$data['main_content'] = 'report_list';
$data['posts'] = $results;
$this->load->view('include/templates', $data);
And I show the data generated by controller in the view page report_list, the code of report_list is
<div id="bg_top">
</div>
<div class = "container" id="content">
<div class="row-fluid">
<div class="span9" id="content_left">
<h2>解题报告列表</h2>
<link href="<?php echo base_url('assets/css/style.css') ?>" rel="stylesheet">
<?php if(!empty($posts) && is_array($posts)):?>
<?php foreach($posts as $post):?>
<div class="entry">
<h2 class="entrytitle"><?php echo anchor($post->link, $post->title)?><span></span></h2>
<div class="entrymeta1">
<div class="meta-date">
<span class="meta-month"><?php echo $post->month?></span>
<span class="meta-day"><?php echo $post->day?></span>
</div>
<span class="meta-author"><?php echo anchor($post->authorlink, $post->author)?></span>
<span class="meta-category"></span>
<span class="meta-comment"></span>
<div class="clear"></div>
</div><!-- [entrymeta1] -->
<div class="entrybody">
<p><?php echo $post->content;?><?php echo anchor($post->link, '阅读全文')?></p>
</div>
<div class="entrymeta3">
</div>
</div><!-- [entry] -->
<?php endforeach;?>
<?php endif;?>
</div>
<div class="span3">
<?php echo "hello world2";?>
</div>
</div>
</div>
The question is where am wrong? why is there errors "Trying to get property of non-object"?
I tried to print the data in the controller, it works quite well.
foreach($results as $post)
{
foreach($post as $key=>$value)
{
echo $key.':'.$value;
echo '<br/>';
}
}
You need to print the variables in the view file in array style like this:
<?php echo anchor($post['link'], $post['title'])?>
Still you can always print the array to view the structure:
<?php echo "<pre>";print_r($posts);echo "</pre>";
My assumption is that
You are expecting $posts as array of objects. But in $posts in some loaction there is no object with property month, day etc. So just before the for loop you should look the type of $posts by
var_dump($posts)
This will give you the clear picture about your error
Change all the variables $post->link to array $post['link']
$post->month
$post->day
every fields that are using in template.
public function actionEquipmentLoanRequestCreate()
{
if(isset($_POST['EquipmentRequest']))
{
$ids = $_POST['EquipmentRequest']['equipID'];
$equipment = Equipment::model()->findAllByPk($ids);
$requests = self::instantiateEquipmentRequests($equipment);
//echo "<pre>";
//die(count($requests)." ".CActiveForm::validate($requests));
$booking = new EquipmentBooking;
if(isset($_POST['EquipmentRequest']) && $_POST['EquipmentBooking'])
{
$booking->attributes = $_POST['EquipmentBooking'];
$requestPostedVars = $_POST['EquipmentRequest'];
//have posted collection of equipment
//need to take count
//request below not really useful???
$equipmentRequests = array();
foreach($requestPostedVars as $request)
{
if(isset($request))
{
$equipmentRequest = new EquipmentRequest('loanRequest');
$equipmentRequest->attributes = $request;
array_push($equipmentRequests,$equipmentRequest);
}
}
$models = $equipmentRequests;
$models[]=$booking;
$this->performAjaxValidation($models);
$booking->equipment = $equipmentRequests;
if ($booking->save()){
self::assignBookingIds($equipmentRequests,$booking);
$this->redirect('index');
}
}
//displays view to create loan request
$this->render('equipment-loan-request',array('requests' => $requests,'booking' => $booking));
} else {
Yii::app()->user->setFlash('error', "You need to select equipment first!");
$this->redirect(array('simulation/equipment'), true);
}
}
public function instantiateEquipmentRequests($equipment)
{
$equipmentRequests = array();
foreach($equipment as $item)
{
$request = new EquipmentRequest('loanRequest');
$request->equipment = $item;
$request->qty = 1;
array_push($equipmentRequests,$request);
}
return $equipmentRequests;
}
form view ignore excess button replacing later -- ive directly tried calling the requests as opposed to just the bookings or both below as well to no avail.
<?php $form=$this->beginWidget('CActiveFormExtended', array(
'id' => 'equipment-booking-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>true,
),
)); ?>
<div class="content-bg">
<?php
echo $form->errorSummary($requests);
if(isset($requests) && count($requests) > 0) {
foreach($requests as $i => $request) {
$this->renderPartial('_requestedEquipment', array("index" => $i, "request" => $request, "form"=> $form));
}
}?>
</div>
<br />
<hr class="brown"/>
<h2>Request Details</h2>
<div class="content-bg">
<h3>Step 1</h3>
<?php echo $form->label($booking,'organisation'); ?>
<?php echo $form->dropDownList($booking, 'organisation', $booking::$organisations,array('id' => 'organisation', 'class' => "selectfield",'empty' => 'Select')); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 2</h3>
<?php echo $form->label($booking,'name'); ?>
<?php echo $form->textField($booking,'name',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'name'); ?>
<?php echo $form->label($booking,'email'); ?>
<?php echo $form->textField($booking,'email',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'email'); ?>
<?php echo $form->label($booking,'phone'); ?>
<?php echo $form->textField($booking,'phone',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'phone'); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 3</h3>
<?php echo $form->label($booking,'address'); ?>
<?php echo $form->textField($booking,'address',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'address'); ?>
<?php echo $form->label($booking,'suburb'); ?>
<?php echo $form->textField($booking,'suburb',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'suburb'); ?>
<?php echo $form->label($booking,'postcode'); ?>
<?php echo $form->textField($booking,'postcode',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'postcode'); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 4</h3>
<div class="five columns alpha">
<?php echo $form->label($booking,'pickupDate'); ?>
<?php echo $form->dropDownDayList($booking, 'pickupDate',array('class' => 'date-day pickup_select','id' => 'pickup')); ?>
<?php echo $form->dropDownYearList($booking,1, 'pickupDate',array('class' => 'date-monthyear pickup_select','id' => 'pickup-month')); ?>
<?php echo $form->hiddenField($booking, 'pickupDate',array('id' => 'pickupData')); ?>
<?php echo $form->error($booking,'pickupDate'); ?>
</div>
<div class="five columns alpha">
<?php echo $form->label($booking,'returnDate'); ?>
<?php echo $form->dropDownDayList($booking, 'returnDate',array('class' => 'date-day return_select','id' => 'return')); ?>
<?php echo $form->dropDownYearList($booking,1, 'returnDate',array('class' => 'date-monthyear return_select','id' => 'return-month')); ?>
<?php echo $form->hiddenField($booking, 'returnDate',array('id' => 'returnData')); ?>
<?php echo $form->error($booking,'returnDate'); ?>
</div>
<br class="clear"/>
</div>
<br />
<div class="content-bg">
<h2>Terms & Conditions</h2>
<p>By submitting this loan enquiry you agree to and acknowledge our Equipment Loan Terms and Conditions.</p>
</div>
<?php echo CHtml::submitButton('Submit'); ?>
<br />
<input class="orange-btn right" type="submit" value="Submit Loan Request">
<?php $this->endWidget(); ?>
</div>
EquipmentRequest partial
<div class="selected-equipment" id="request_<?php echo $request->equipment->equipName; ?>">
<div class="equipment-selected"><?php echo $request->equipment->equipName; ?></div>
<div class="equipment-qty"><?php echo $form->textField($request, "[$index]qty", array('value' => 1,'class' => 'requestQuantity')); ?></div>
<?php echo $form->error($request,"[$index]qty"); ?>
<div class="equipment-update"><span>Remove</span></div>
<?php echo $form->hiddenField($request, "[$index]equipID",array('value' => $request->equipment->equipID)); ?>
<?php echo $form->error($request,"[$index]equipID"); ?>
<br class="clear">
</div>
EDIT
Please note I have rectified the above issue. Was mainly caused by an incorrect usage of performAjaxValidate, which I have now set to call both the booking and the collection of equipmentRequests.
This is now letting me get 2 validation error message objects back, 1 for both models. however only the booking model is being passed to the error summary div.
#bool.dev appreciate your assistance so far, any ideas with the above, have tried merging the collection of equipment request objects and booking object to the one argument call in errorSummary
I've edited the above to show updated controller actions and views
When you want errorSummary() for more than one model, use:
$form->errorSummary(array($model1,$model2,$model3));