How to release pagination in "GET" search? - php

I use this code For search in database:
<?php
if(isset($_GET['keywords'])) {
$keywords = $CONNECT->escape_string($_GET['keywords']);
if(!$keywords){
echo("<script>location.href = '/news';</script>");
//if javascript disabled
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
?>
<div class="found">founded<?php echo $Query->num_rows; ?> </div>
</div>
</div>
<div class="ncontent">
<div class="keyword">phrase: "<p><?php echo htmlspecialchars($keywords); ?></p>"</div>
<?php
if($Query->num_rows){
while ($r = $Query->fetch_object()){
?>
<div class="nline"><a href="/news/content/id/<?php echo $r->id; ?>"><div class="prewnews">
<div class="imgh1"><img src="<?php echo $r->himg; ?>"/></div>
<span><i class="fa fa-heart-o" aria-hidden="true"> <p>124</p></i><hr style="background:#cd4436; border:0; height:3px" /><i class="fa fa-eye" aria-hidden="true"> <p><?php echo $r->readed; ?></p></i> </span>
<h3><?php echo $r->title; ?></h3>
</div>
</a>
</div>
<?php
}
}else echo '<div class="notfound"><img src="/resource/img/notfound.png" alt=""></div>';
}else {echo("<script>location.href = '/news';</script>");
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
?>
Search form:
<form action="/search" method="GET">
<input class="search red" placeholder="search..." type="search" name="keywords" autocomplete="off">
</form>
So, after search i get link like this: /search?keywords=test+search+phrase
As I think i can do like this: /search?keywords=test+search+phrase&page2
or like this: /page2/search?keywords=test+search+phrase
What you advise, which way pagination?
And can you provide links that will help to realize them?
Or anyone of you can help me here?

The following pagination solution will show at most 10 search results per page, and for navigating rest of the search results, use pagination links. The solution will show at most 5 links per page, kind of like this:
// user is on 1st page
1 2 3 4 5 ...
-
// user is on 7th page
... 5 6 7 8 9 ...
-
// user is on 10th page(lets say, 10th page is the last page)
... 6 7 8 9 10
-
So, to implement this pagination functionality, you need to make few changes in your code. Keep your HTML search form as it is, and change your PHP code in the following way,
First check if there's any ...&page=123 exists or not in the URL, and based on that, process your $_GET superglobal like this way,
if(isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
Define rows per page and calculate offset based on that, like this:
$per_page = 10; // rows per page
$offset = ($current_page - 1) * $per_page; // offset
And fetch table results based on these $per_page and $offset values, like this:
$Query = mysqli_query($CONNECT, "SELECT ... WHERE `content` LIKE ... LIMIT ". $per_page . " OFFSET " . $offset);
Now to display pagination links below the search results, follow the below procedure:
Get total number of rows from the queried result set and calculate total number of page/pagination links to display, like this:
// display pagination links
$Query = mysqli_query($CONNECT, "SELECT ... FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
if($Query->num_rows){
$total_records = $Query->num_rows;
$total_pages = ceil($total_records / $per_page);
...
Find the superset range of pages, like 1-10, or 1-20 etc. For example, if $total_pages = 20 then this superset range would be 1-20. The code for this step is this:
// superset range of pages
$superset_range = range(1, $total_pages);
Find the subset range of pages to display, like 1-5, or 3-7 etc. For example, if $total_pages = 20 then this subset range would be 1-5, or 3-7, or 6-10 etc., it can be any consecutive five pages between 1 and 20. Also, adjust this range whenever necessary. The code for this step is this:
// subset range of pages to display
$subset_range = range($current_page - 2, $current_page + 2);
// adjust the range(if required)
foreach($subset_range as $p){
if($p < 1){
array_shift($subset_range);
if(in_array($subset_range[count($subset_range) - 1] + 1, $superset_range)){
$subset_range[] = $subset_range[count($subset_range) - 1] + 1;
}
}elseif($p > $total_pages){
array_pop($subset_range);
if(in_array($subset_range[0] - 1, $superset_range)){
array_unshift($subset_range, $subset_range[0] - 1);
}
}
}
Finally, display the pagination links and dots accordingly. The code for this step is this:
// display intermediate pagination links
if($subset_range[0] > $superset_range[0]){
echo "... ";
}
foreach($subset_range as $p){
if($p == $current_page){
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "' style='text-decoration: underline;'>$p</a>";
}else{
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "'>$p</a>";
}
}
if($subset_range[count($subset_range) - 1] < $superset_range[count($superset_range) - 1]){
echo " ... ";
}
Here's the complete code:
<?php
if(isset($_GET['keywords'])) {
$keywords = $CONNECT->escape_string($_GET['keywords']);
if(!$keywords){
echo("<script>location.href = '/news';</script>");
//if javascript disabled
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
if(isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
$per_page = 10;
$offset = ($current_page - 1) * $per_page;
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%' LIMIT ". $per_page . " OFFSET " . $offset);
?>
<div class="found">founded<?php echo $Query->num_rows; ?> </div>
</div>
</div>
<div class="ncontent">
<div class="keyword">phrase: "<p><?php echo htmlspecialchars($keywords); ?></p>"</div>
<?php
if($Query->num_rows){
while ($r = $Query->fetch_object()){
?>
<div class="nline">
<a href="/news/content/id/<?php echo $r->id; ?>">
<div class="prewnews">
<div class="imgh1">
<img src="<?php echo $r->himg; ?>"/>
</div>
<span>
<i class="fa fa-heart-o" aria-hidden="true">
<p>124</p>
</i>
<hr style="background:#cd4436; border:0; height:3px" />
<i class="fa fa-eye" aria-hidden="true">
<p><?php echo $r->readed; ?></p>
</i>
</span>
<h3><?php echo $r->title; ?></h3>
</div>
</a>
</div>
<?php
}
// display pagination links
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
if($Query->num_rows){
$total_records = $Query->num_rows;
$total_pages = ceil($total_records / $per_page);
if($total_records > $per_page){
echo "<center>";
// Superset range of pages
$superset_range = range(1, $total_pages);
// subset range of pages to display
$subset_range = range($current_page - 2, $current_page + 2);
// adjust the range(if required)
foreach($subset_range as $p){
if($p < 1){
array_shift($subset_range);
if(in_array($subset_range[count($subset_range) - 1] + 1, $superset_range)){
$subset_range[] = $subset_range[count($subset_range) - 1] + 1;
}
}elseif($p > $total_pages){
array_pop($subset_range);
if(in_array($subset_range[0] - 1, $superset_range)){
array_unshift($subset_range, $subset_range[0] - 1);
}
}
}
// display intermediate pagination links
if($subset_range[0] > $superset_range[0]){
echo "... ";
}
foreach($subset_range as $p){
if($p == $current_page){
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "' style='text-decoration: underline;'>$p</a>";
}else{
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "'>$p</a>";
}
}
if($subset_range[count($subset_range) - 1] < $superset_range[count($superset_range) - 1]){
echo " ... ";
}
echo "</center> ";
}
}
}else{
echo '<div class="notfound"><img src="/resource/img/notfound.png" alt=""></div>';
}
}else {
echo("<script>location.href = '/news';</script>");
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>

Related

Pagination in PHP MySQL not limiting data and neither going to next page

I have listing in my HTML which is displayed from database. My listing code is like below:
<?php
require('admin/db_config.php');
$sql = "SELECT * FROM image_gallery";
$images = $mysqli->query($sql);
while($image = $images->fetch_assoc()){
?>
<div class="aamir"><span><img style="height:40px; width:55px; " class="img-responsive" alt="" src="admin/uploads/<?php echo $image['image'] ?>" /></span><small><?php echo $image['title']; ?></small><strong style="width:40%; height: 35%;"><em class="icon icon-chevron-down"></em><p style="margin-top: -5%;"> <?php echo $image['description']; ?> </p></strong>
<a
class="zayan" target="_blank" href="<?php echo $image['url']; ?>">VISIT</a>
</div>
<?php } ?>
Now I have given pagination for the same because the data is too much and I want it to go to next page. So I have given pagination. Pagination code is below:
<?php
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("localhost","root","","sample");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM image_gallery";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM image_gallery LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($res_data)){
//here goes the data
}
mysqli_close($conn);
?>
<ul class="pagination">
<li>First</li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
Prev
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
Next
</li>
<li>Last</li>
</ul>
But still the pagination is not working, no error is shown, the whole data is being displayed in one page and the pagination is like static.

How to paginate search result using php pdo?

I am creating a pagination for search result all looks fine on first loading page,
but when I click on paginated links then it show me a white page (search page but without entries in).
simply with no results found from my data
This is the site search box in index.php
<form action="search/" method="post">
<input type="text" name="search" placeholder="word..." required />
<input type="submit" name="submit_search" class="search-btn" value="" />
</form>
Here is my setup for htaccess pagination:
RewriteRule ^search/page/(.*)$ search.php?page=$1 [L,NC]
it looks fine on browser.
Here is my search page codes:
<?php
if(isset($_POST['submit_search']) && !empty($search)){
$search = htmlspecialchars(strip_tags($_POST['search']), ENT_QUOTES);
$perpage = intval("12");
$n_stmt = $pdo->prepare("SELECT * FROM posts");
$n_stmt->execute();
$total_posts = $n_stmt->rowCount();
$total_pages = ceil($total_posts/$perpage);
$page = !empty($_GET['page']) && intval($_GET['page']) ? (int) intval($_GET['page']) : intval("1");
if($page < intval("1")) $page = intval("1");
if($page > $total_pages) $page = $total_pages;
$limit = ($page - intval("1")) * $perpage;
$pages_to_show = intval("10");
$stmt = $pdo->prepare("SELECT * FROM posts WHERE title LIKE :search OR subject LIKE :search OR descriptions LIKE :search OR keywords LIKE :search ORDER BY created DESC LIMIT :limit, :perpage");
$stmt->bindValue(":search","%".$search."%", PDO::PARAM_STR);
$stmt->bindValue(":limit",$limit, PDO::PARAM_INT);
$stmt->bindValue(":perpage",$perpage, PDO::PARAM_INT);
if($stmt->execute()){
if($stmt->rowCount() > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){?>
<div class="news_box">
<a href="<?php echo htmlspecialchars($row['news_url']);?>/" title="<?php echo htmlspecialchars($row['title']);?>">
<div class="title"><h2><?php echo htmlspecialchars($row['title']);?></h2></div>
<div class="image">
<img src="images/posts/<?php echo htmlspecialchars($row['img']);?>" alt="<?php echo htmlspecialchars($row['title']);?>"/></div>
<div class="spot"><?php echo htmlspecialchars($row['subject']);?></div>
</a>
</div>
<?php
}
}
}
unset($stmt);
?>
Here is my pagination part:
<div class="pagination">
<?php if($page >1){?>
First
previous
<?php } for($i = $page - $pages_to_show; $i < $page + $pages_to_show + 1; $i++){
if($i > 0 and $i <= $total_pages){
if($i == $page){?>
<?php echo intval($i);?>
<?php }else{?>
<?php echo $i;?>
<?php
}
}
?>
<?php } ?>
<?php if($page != $total_pages){?>
Next
Last
<?php } ?>
</div>

Product Refine filter by categories, price and regions

I am still learning web development and I am working on a project in order to learn how to develop a complete website with all functionalities. I am currently trying to implement the product refine filter by categories, condition, region and price. I started doing the filter according to categories and regions only, to see how I could go about but my attempt to do it failed. Whenever I check a box, itfetches the categoryId in the url but gives me an error about sql syntax.
The error message received:
I have 4 tables
ads table with adId, title, catId, regionId, price, condition, description
category table with catId, catName
region table with regionId, regionName
images table with imageId,adId,path, preview
Can anyone help me to find a solution to my problem?
Here is my class file
public function getAllCat(){
$query = "SELECT * FROM category ORDER BY catId";
$result = $this->db->select($query);
return $result;
}
public function getAllRegion(){
$query = "SELECT * FROM region ORDER BY regionId";
$result = $this->db->select($query);
return $result;
}
public function getAllAds(){
$query = "SELECT * FROM ads ORDER BY adId DESC";
$result = $this->db->select($query);
return $result;
}
public function getPreviewImage($id){
$query = "SELECT * FROM images WHERE adId = $id AND preview = '1' ";
$image = $this->db->select($query);
return $image;
}
Here is my allads.php file
<?php
//declaration array varible
$filtercategory = array();
$filterregion = array();
//finding query string value
if(isset($_REQUEST['filtercategory'])){
//query string value to array and removing empty index of array
$filtercategory = array_filter(explode("-",$_REQUEST['filtercategory']));
}
if(isset($_REQUEST['filterregion'])){
$filterregion = array_filter(explode("-",$_REQUEST['filterregion']));
}
?>
<main class="cd-main-content">
<div class="Ads-Container">
<?php
//Pagination start
$query = "SELECT COUNT(adId) FROM ads";
$result = $db->select($query);
$row = mysqli_fetch_row($result);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 20;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
?>
<?php
$query = "SELECT * FROM ads ORDER BY adId DESC $limit";
//filter query start
if(!empty($filtercategory)){
$categorydata =implode("','",$filtercategory);
$query .= " and catId in('$categorydata')";
}
if(!empty($filterregion)){
$regiondata =implode("','",$filterregion);
$query .= " and regionId in('$regiondata')";
}
//filter query end
$post = $db->select($query);
if($post){
while($result = $post->fetch_assoc()){
?>
<div class="ads-column_2">
<div class="ads-column-thumbnail">
<?php
$preview = $ad->getPreviewImage($result["adId"]);
if($preview){
while($rresult = $preview->fetch_assoc()){
?>
<img src="/afro-circle/<?php echo $rresult['path']?>" alt="" class="image-responsive">
<?php } } ?>
<div class="ads-preview-details">
<center>
<h4><?php echo $result['title']; ?></h4>
<h4 class="">FCFA <?php echo number_format($result['price']); ?></h4>
</center>
</div>
<div class="space-ten"></div>
<div class="btn-ground text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#product_view">Quick View</button>
</div>
<div class="space-ten"></div>
</div>
</div>
<?php } } ?>
</div>
<!-- /.row -->
<div class="row" style="text-align: center;">
<?php
// This shows the user what page they are on, and the total number of pages
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'First Page ';
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= '<span>'.$pagenum.'</span> ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
$paginationCtrls .= ' Last Page ';
}
}
?>
<div class="pagination">
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</div>
<!-- /.row -->
<div class="cd-filter filter-is-visible">
<form>
<div class="cd-filter-block">
<h4>Categories <span class="spanbrandcls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<ul class="cd-filter-content cd-filters list">
<?php
$getCategory = $category->getAllCat();
if($getCategory){
while($result = $getCategory->fetch_assoc()){
?>
<li>
<input type="checkbox" class="filter filtercategory" value="<?php echo $result['catId']; ?>" <?php if(in_array($result['catName'],$filtercategory)){ echo"checked"; } ?> >
<label class="checkbox-label" id="Category" ><?php echo $result['catName']; ?></label>
</li>
<?php } } ?>
</ul> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Size <span class="spansizecls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<div class="cd-filter-content">
<div class="cd-select cd-filters">
<select class="filter scheck" name="subcatId">
<option data-type="sizes" value="">Item Condition</option>
<option data-type="sizes" value="1">New</option>
<option data-type="sizes" value="2">Used</option>
</select>
</div> <!-- cd-select -->
</div> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Region <span class="spancolorcls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<ul class="cd-filter-content cd-filters list">
<?php
$getRegion = $region->getAllRegion();
if($getRegion){
while($result = $getRegion->fetch_assoc()){
?>
<li>
<input type="radio" class="filter filterregion" value="<?php echo $result['regionId']; ?>" <?php if(in_array($result['regionName'],$filterregion)){ echo"checked"; } ?>>
<label class="radio-label" for="radio1"><?php echo $result['regionName']; ?></label>
</li>
<?php } } ?>
</ul> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
</form>
<i class="fa fa-close"></i> Close
</div>
<i class="fa fa-filter"></i> Search by:
<div class="clear"></div>
Here is my JS
<script>
$(function(){
$('.filter').click(function(){
var filtercategory = multiple_values('filtercategory');
var filterregion = multiple_values('filterregion');
var url ="allads.php?filtercategory="+filtercategory+"&filterregion="+filterregion;
window.location=url;
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val.join('-');
}
The problem lies in the following section of the code:
$query = "SELECT * FROM ads ORDER BY adId DESC $limit";
//filter query start
if(!empty($filtercategory)){
$categorydata =implode("','",$filtercategory);
$query .= " and catId in('$categorydata')";
}
if(!empty($filterregion)){
$regiondata =implode("','",$filterregion);
$query .= " and regionId in('$regiondata')";
}
The code insert the filter criteria at the en of the sql statement, which means after the limit. So, the actual sql statement looks something like as follows:
SELECT * FROM ads ORDER BY adId DESC LIMIT 10, 10 and catId in('4')
The correct sql code would look something like:
SELECT * FROM ads WHERE catId in('4') ORDER BY adId DESC LIMIT 10, 10
You must modify your php code to generate valid sql code. While debugging, add code that prints out the full sql statement to see the full sql ststement before it is executed.
Also, your code is wide open to sql injection attacks. Pls use prepared statements or other techniques to prevent such attacks.

Pagination script added php page isn't loading or showing any error

I tried to add a pagination script to my existing php page of sql queries.
But after adding the script the page is kept on loading without showing any content or error.
My code goes as:
<?php include('db.php'); ?>
<?php // define how many results you want per page
$results_per_page = 10;
// find out the number of results stored in database
$sql10='SELECT * FROM smf_messages';
$result10 = mysqli_query($conn, $sql10);
$number_of_results = mysqli_num_rows($result10);
// determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;
?>
Now the sql query codes to get the data from the respective tables...
<?php
$sql2 = "SELECT * FROM smf_log_digest WHERE note_type = 'topic' ORDER BY id_msg DESC LIMIT 420";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$number = $row2["id_msg"];
?>
This query relates to the content from which table to be retrieved..
<?php
// retrieve selected results from database and display them on page
$sql20='SELECT * FROM smf_messages WHERE id_msg = $number AND id_board = 4 LIMIT ' . $this_page_first_result . ',' . $results_per_page;
$result20 = mysqli_query($conn, $sql20);
while($row20 = mysqli_fetch_array($result20)) {
$member = $row20["id_member"];
$replies = $row20["id_topic"];
?>
<?php
$sqlstep1 = "SELECT COUNT(*) AS total FROM smf_log_digest WHERE note_type = 'reply' AND id_topic = $replies";
$rowNumstep1 = mysqli_query($conn, $sqlstep1);
$countstep1 = mysqli_fetch_assoc($rowNumstep1);
?>
// Body
<article class="well btn-group-sm clearfix">
<div class="topic-desc row-fluid clearfix">
<div class="col-sm-2 text-center publisher-wrap">
<img src="assets/images/profile.png" alt="" class="avatar img-circle img-responsive">
<h5><?php echo $row3["poster_name"]; ?></h5>
<small class="online">Member</small>
</div>
<div class="col-sm-10">
<header class="topic-footer clearfix">
<!-- end tags -->
</header>
<!-- end topic -->
<h4> <?php echo $row20["body"]; ?></h4>
<div class="blog-meta clearfix">
<small><?php echo $countstep1["total"]; ?> Replies</small>
<small><?php echo date('m/d/Y', $row20["poster_time"]); ?></small>
</div>
View the topic →
</div>
</div>
</article>
//end of body
<?php
}
// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
echo '' . $page . ' ';
}
?>
<?php }
} else {
echo "";
}
?>
Please note that the data base connections are all checked and are right..
Any help is appreciated..
add this on top then check for error.
error_reporting(E_ALL);
ini_set('desplay_errors','1');

Limiting chars for a content

I have content, in which I'm trying to limit using this query:
if(strlen($news_content < 35)){
$news_content = substr($news_content, 0, 30) . "";
}
But for some reason, it isn't limiting the chars.. Or It's my coding(which I'm sure is why it's not working) that's off a bit.
here's the full code:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
$comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM articles WHERE id='" . mysql_real_escape_string($_GET['id']) . "' LIMIT 1");
$grab = mysql_query("SELECT id, news_title, news_content, news_author, news_day, news_month, news_year, news_date FROM articles ORDER BY id DESC limit 3");
$news_day =$row['news_day'];
$news_month =$row['news_month'];
$news_year =$row['news_year'];
$news_content =$row['news_content'];
if(strlen($news_content < 35)){
$news_content = substr($news_content, 0, 30) . "";
}
elseif (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no articles posted!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
<div class="post-container">
<div class="post">
<div class="left">
<div class="date"><span class="day"><?php echo $row['news_day'] ?></span> <span class="month"><?php echo $row['news_month'] ?></span> <span class="year"><?php echo $row['news_year'] ?></span></div></div>
<div class="postcontent"><h5 class="posttitle"><?php echo stripslashes($row['news_title']); ?></h5>
<?php echo $row['news_content'] ?>
<p> (READ MORE)</p>
<p>Comments (<?php echo $comments ?>)</p>
</div>
</div>​
</div>
I'm simply trying to limit the "news_content", but I don't know where it is that I'm messing up at. Thanks!
Try changing the first line from:
if(strlen($news_content < 35)) {...}
To:
if(strlen($news_content) > 35) {
That includes switching the < to > , as presumably you want to truncate if it's longer than 35 characters rather than less ?
I think generally there are better ways to truncate though. Your approach could just cut text off in the middle of a word abruptly. Have a look at http://www.the-art-of-web.com/php/truncate/#.UNEbnmdaerI or http://www.ambrosite.com/blog/truncate-long-titles-to-the-nearest-whole-word-using-php-strrpos for other ideas.
In the html code you don't reference <?php echo $news_content?>, but <?php echo $row['news_content']?>, thus ignoring the shortened version.
Combine that with the proposed change to change the strlen($row['news_content']) < 35 to > 35 to get it working.
Following should work:
if (strlen($news_content) < 35))

Categories