Pagination in PHP blog - php

I am creating a blog in PHP (trying to keep it close to OOP) and am struggling with getting pagination to work on the page that displays all posts.
The code for the blog.php in question is
<?php
require_once("includes/init.php");
$pagetitle = "Blog";
//include header.
require_once("includes/template/header.php");
// initialise script
$blog = new Blog($db);
$parsedown = new Parsedown();
// load blog posts
$posts = $blog->get_posts();
?>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Blog Home</h1>
</div>
</div>
<div class="row">
<div class="col-lg-8">
<?php foreach ($posts as $post) { ?>
<h1><?php echo $post['title']; ?>
</h1>
<p class="lead">by <?php echo $post['author']; ?>
</p>
<hr>
<p><i class="fa fa-clock-o"></i> Posted on <?php echo date("d/m/Y", strtotime($post['date'])); ?> At <?php echo date("H:i", strtotime($post['date'])); ?> in <?php
$categories = $blog->get_categories($post['id']);
$links = array();
foreach ($categories as $category) {
$links[] = "<a href='blog-categories.php?id=".$category['category_slug']. "'>".$category['category_name']."</a>";
}
echo implode(", ", $links); ?></p>
<hr>
<p><?php $content = $parsedown->parse($post['content']); echo substr($content,0,445) ; ?></p>
<a class="btn btn-primary" href="<?php echo $post['slug']; ?>">Read More <i class="fa fa-angle-right"></i></a>
<a class="btn btn-primary" href="<?php echo $post['slug']; ?>#disqus_thread"><i class="fa fa-angle-right"></i></a>
<hr>
<?php }
?>
</div>
What can I add either to the Blog class or put in a new class to allow blog.php to only show the first 5 results and then give a 'next' link to view the next set of 5? I'm not worried about displaying the total number of pages.
As the class is very large, it can be viewed at http://pastebin.com/qN5ii2Ta.

You are currently using a method get_posts(). You could redefine this method to accept a starting point to begin gathering posts from. With this starting point defined you can LIMIT how many posts are returned in your SQL query.

Related

Page Goes Blank With Function On Php

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.

How sort data in view page in codeigniter

I am getting the data in a view page. Now I want to search it with some data coming form a text box in the same view page.
What should I do? Can I use ajax or jQuery?
This is my view page
<li class="">Doctors</li>
</ol>
<div class="list col-xs-8">
<div class="col-md-8 col-md-offset-2">
<?php echo $this->session->flashdata('msg'); ?>
</div>
<ul>
<input type="text" name="search_data" placeholder="Search ..." class="form-control" id="search_data" onkeyup="ajaxSearch();"style=" height: 50px; width: 200px !important;">
<?php
if(isset($doc)):
foreach ($doc as $row):
?>
<li>
<div class="imgt"><img src="<?php echo base_url("./resources/images/"); if($row->dr_img) echo $row->dr_img;
else echo "no-img.jpg"; ?>" height="90px" width="82px">
</div>
<div class="text">
<h3><b>Dr. <?php echo $row->dr_name;?></b><br></h3>
<p><?php echo $row->spec_specialise; ?><br><?php echo $row->district;?><br><?php echo $row->state;?></p>
</div>
<div class="text"></div>
<div class="link">
<i class="ace-icon fa fa-eye sym"></i>View</div>
</li>
<?php endforeach;
endif;
?>
</ul>
<div class="space"></div>
</div>
</div>
<div class="pdt_rightt">
<center>
</center>
</div>
In the title of your post you say you want to "sort" the data, but in the description you say you want to "search" it.
I would recommend doing this without Ajax to begin with to get an understanding of the fundamentals.
Your View could look like this:
<?php echo form_open( current_url() ); ?>
<h2>Search</h2>
<input type="text" name="search" placeholder="Enter search word" />
<button>Search</button>
<?php echo form_close(); ?>
<?php if (isset($docs)) : ?>
<p>
<a href="<?php echo current_url(); ?>?sort=dr_name&search=<?php echo html_escape( urlencode( $search ) ); ?>">
Sort by name
</a>
</p>
<ul>
<?php foreach ($docs as $row) : ?>
<li><?php echo html_escape( $row->dr_name ); ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Then your Controller would be like this:
public function index() {
$search = $this->input->get_post('search');
$sort = $this->input->get('sort');
$docs = $this->doc_model->get_docs( $search, $sort );
$data = array(
'search' => $search,
'sort' => $sort,
'docs' => $docs
);
$this->load->view('docs', $data);
}
Your Model will then need to fetch all Doctors if $search is null, or query the Doctors' names by $search if it's not null. Likewise if $sort is null then you'd order by a default field (date created for example).
If you have lots of results then you'd also want to look at CI's Pagination class to span the results over several pages.
You can achieve all of this using Ajax but if you have lots of results you are still going to need to call your Controller and Model, similar to the above, to do the heavy lifting.

Codeigniter - How to retrieve specific data on view after getting result array from model

So this is the function from model Publicationdata that sends the result array to controller based on the author id that controller provides it->
public function getSpPubData($tId)
{
$this->db->order_by("pub_year", "desc");
$q = $this->db->get_where('rsc_faculty_publications', array('pub_author_id' => $tId));
$error = $q->num_rows() > 0 ? FALSE : TRUE;
if ($error === FALSE)
{
return $q->result();
}
else{
return $error;
}
}
now on controller i am saving the array as-
$data['pubData'] = $this->Publicationdata->getSpPubData("10006);
the rsc_faulty_publications table has a field pub_year.. now on view when I am accessing $pubData on view.. i want to print the publications yearwise. they will be printed in a loop when the current year publications will be at top.. so what I want is to fetch the yearwise publications from $pubData through loop.. the view is like this-
<?php
for($i=0;$i<sizeof($pubData);$i++){ ?>
<div class="panel panel-info">
<div class="panel-heading" data-toggle="collapse" data-parent="#accordion<?php echo $pubData[$i]->pub_year; ?>" href="#year<?php echo $pubData[$i]->pub_year; ?>" title="Click to expand/collapse">
<h4 class="panel-title">Publication Year: <?php echo $pubData[$i]->pub_year; if($pubData[$i]->pub_year==date('Y')){echo " (".sizeof($pubData)." Publications until now)";}?></h4>
</div>
<div id="year<?php echo $pubData[$i]->pub_year; ?>" class="panel-collapse collapse">
<div class="panel-body">
<?php while($pubData[$i]->pub_year==$pubData[$i+1]->pub_year){
?>
<div class="well well-info">
<p><?php echo $pubData[$i]->pub_title; ?></p>
<p><?php echo $pubData[$i]->pub_authors; ?></p>
<p><?php echo $pubData[$i]->pub_publisher; ?></p>
</div>
<?php
}?>
</div>
</div>
</div>
<?php } ?>
First load the view file in controller and pass the data.
$this->load->view('view_file', $data);
Use following code in the view file to retrieve the data.
foreach($pubData->brands as $brand): ?>
after getting the value from model say
$data['value']=$this->model1->getValue();
Now you can pass the value you obtained to view page like this
$this->load->view('viewpagename',$data);
Now in the view page you can easily access it using the array name you passed .ie value. So in the view page do
foreach($value as $val){
print what you want here
}
<?php $i=0;
$n=0;
$brands = array('info','warning','primary','success');
$len=sizeof($pubData);
while($i<$len){ ?>
<?php if($i==0||$i-1!==-1 && $pubData[$i]->pub_year!==$pubData[$i-1]->pub_year){ ?>
<div class="panel panel-<?php echo $brands[$n];?>">
<div class="panel-heading" data-toggle="collapse" data-parent="#accordion1" href="#year<?php echo $pubData[$i]->pub_year; ?>" title="Click to expand/collapse">
<h4 class="panel-title">Publication Year: <?php echo $pubData[$i]->pub_year; if($pubData[$i]->pub_year==date('Y')){echo " (".sizeof($pubData)." Publications until now)";}?></h4>
</div>
<div id="year<?php echo $pubData[$i]->pub_year; ?>" class="panel-collapse collapse">
<div class="panel-body">
<?php
}?>
<div class="well well-<?php echo $brands[$n];?>">
<p><?php echo $pubData[$i]->pub_title; ?></p>
<p><?php echo $pubData[$i]->pub_authors; ?></p>
<p><?php echo $pubData[$i]->pub_publisher; ?></p>
</div>
<?php if($i==$len-1 || $i+1!==$len && $pubData[$i]->pub_year!==$pubData[$i+1]->pub_year){
if($n==3){$n=0;}else{$n++;} ?>
</div>
</div>
</div >
<?php } $i++;
} ?>

Display nav list of content is available with php

I've got this PHP code:
<div class="connect_wrap <?php echo $this->class; ?> block" <?php echo $this->cssID; ?>>
<?php if(!$this->empty): ?>
<?php foreach($this->entries as $entry): ?>
<div class="entry block <?php echo $entry->class; ?>">
<div class="tab">
<ul class="tabs">
<li class="tab-link current" data-tab="Kunden">Kunden</li>
<li class="tab-link" data-tab="Loesungen">Lösungen</li>
</ul>
<?php
$this->import('Database');
$pName = $entry->field('name')->value();
$result = \Database::getInstance()->prepare("SELECT * FROM kunden WHERE partner=?")->execute($pName);
?>
<?php if($result->numRows):?>
<div id="Kunden" class="tab-content current">
<?php while($result->next()) { ?>
<div class="items">
<a href="{{env::url}}/kunden-detail/<?php echo $result->alias; ?>">
<div class="logo">
<img src="<?php $objFile = \FilesModel::findByUuid($result->logo); echo $objFile->path;?>"width="180" height="135">
</div>
</a>
</div>
<?php } ?>
</div>
<?php endif;?>
<?php
$this->import('Database');
$pName = $entry->field('name')->value();
$result = \Database::getInstance()->prepare("SELECT * FROM solutions WHERE solution_provider=?")->execute($pName);
?>
<?php if($result->numRows):?>
<div id="Loesungen" class="tab-content">
<?php while($result->next()) { ?>
<div class="items">
<a href="{{env::url}}/synaptic-commerce-solution/<?php echo $result->alias; ?>">
<div class="logo">
<img src="<?php $objFile = \FilesModel::findByUuid($result->logo); echo $objFile->path;?>"width="180" height="135">
</div>
</a>
</div>
<?php } ?>
</div>
<?php endif;?>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<?php endif;?>
In that code, I've got two DB queries. My problem is, if there is no data for both queries, the div with the class "connect_wrap" should not be displayed.
How can I do that?
Thanks in advance.
do you want to check if the query has data in it and its not empty ? if so try num_rows it will return the number of rows that the query found/affected for example to check if th query returned one or more rows
if($result->num_rows >= 1) {
//do stuf
} else {
// no result found
}
Move the query execution up or preferably: not within the html but in a different file/class. Then add a check before the content_wrap div: if($kundenResult->num_rows >= 1 || $solutionsResult->num_rows >= 1). If you just keep the individual checks like you already have, it will only show the content_wrap div if either or both of the queries return rows of data.

Looping over PHP array several times at once whilst not showing same data

I am creating some jQuery functionality on my website whereas an array of Facebook posts and Tweets is looped through to show on the front page.
I have 5 boxes on my front page which I need 5 to show random elements from this array at the same time, then I using some jQuery cycle functionality to cycle through this array. The only issue is, as I am looping over this array 5 times (with each box) and there are only 20 items in this array it can show repeated data.
To help explain this more here is my code:
<?php
$social_feeds = array_merge($tweets_feed, $facebook_feeds);
$social_feeds_arranged = $tweets_feed_instance->sortArrayItemsByDate($social_feeds);
?>
<div id="social_box_item1" class="social_box_item">
<?php foreach($social_feeds_arranged as $item) { ?>
<a class="item">
<?php echo $item['text'] ?>
</a>
<?php } ?>
</div>
<div id="social_box_item2" class="social_box_item">
<?php foreach($social_feeds_arranged as $item) { ?>
<a class="item">
<?php echo $item['text'] ?>
</a>
<?php } ?>
</div>
<div id="social_box_item3" class="social_box_item">
<?php foreach($social_feeds_arranged as $item) { ?>
<a class="item">
<?php echo $item['text'] ?>
</a>
<?php } ?>
</div>
<div id="social_box_item4" class="social_box_item">
<?php foreach($social_feeds_arranged as $item) { ?>
<a class="item">
<?php echo $item['text'] ?>
</a>
<?php } ?>
</div>
<div id="social_box_item5" class="social_box_item">
<?php foreach($social_feeds_arranged as $item) { ?>
<a class="item">
<?php echo $item['text'] ?>
</a>
<?php } ?>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#social_box_item1').cycle({
});
jQuery('#social_box_item2').cycle({
});
jQuery('#social_box_item3').cycle({
});
jQuery('#social_box_item4').cycle({
});
jQuery('#social_box_item5').cycle({
});
});
</script>
What I need to happen I think is for the first loop to push the item it is displaying ot the back of the array, so when the second loop accesses the first item it will not show the same array item, the same with the 3rd, 4th and 5th loops. I have attempted to do this using array_push and array_shift but can't seem to get it working.
Does anybody have any ideas or can help point out where I am going wrong?
Those loops are not needed then. You can access those array items one by one, if you meant that. Try this:
$social_feeds = array_merge($tweets_feed, $facebook_feeds);
$social_feeds_arranged = $tweets_feed_instance->sortArrayItemsByDate($social_feeds);
?>
<div id="social_box_item1" class="social_box_item">
<a class="item">
<?php echo $social_feeds_arranged[0]['text']; ?>
</a>
</div>
<div id="social_box_item2" class="social_box_item">
<a class="item">
<?php echo $social_feeds_arranged[1]['text']; ?>
</a>
</div>
<div id="social_box_item3" class="social_box_item">
<a class="item">
<?php echo $social_feeds_arranged[2]['text']; ?>
</a>
</div>
<div id="social_box_item4" class="social_box_item">
<a class="item">
<?php echo $social_feeds_arranged[3]['text']; ?>
</a>
</div>
<div id="social_box_item5" class="social_box_item">
<a class="item">
<?php echo $social_feeds_arranged[4]['text']; ?>
</a>
</div>

Categories