Convert old MySql Pagination to PDO

I trying to switch over to connecting to my database via PDO, but when doing so all my old working code needs to be rewrote. I’m trying to make a new section on my website and include pagination.

The pagination part is were I’m having the most trouble.

I have this old mysql pagination query here:

[php]include_once($_SERVER[‘DOCUMENT_ROOT’] . “/includes/database.php”);

foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}

$category = @$_REQUEST[“category”] ? $_REQUEST[“category”] : null;
$images = mysql_query(
$category ?
sprintf(
“SELECT * FROM htp_news WHERE date = ‘%s’”,
$category
) :
“SELECT * FROM htp_news”
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 2;
$page = @$_REQUEST[“page”] ? $_REQUEST[“page”] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>

    <?php if ($category) { $images = mysql_query(sprintf( "SELECT * FROM htp_news WHERE date = '%s' ORDER BY date DESC LIMIT %d, %d", $category, ($page - 1) * $per, $per )); } else $images = mysql_query(sprintf( "SELECT * FROM htp_news ORDER BY date DESC LIMIT %d, %d", ($page - 1) * $per, $per )); while ($image=mysql_fetch_array($images)) { ?>
  • ">
    <?=$image["title"] ?>
    <?= date("F d, Y", strtotime($image["date"])); ?>
    .articletext img{width:100%; height:auto;}<?php $string = $image["description"]; $max = 300; // or 200, or whatever if(strlen($string) > $max) { // find the last space < $max: $shorter = substr($string, 0, $max+1); $string = substr($string, 0, strrpos($shorter, ' ')).'...'; } echo $string; ?>
  • <?php } ?>
<?php /* style me */ /*pagination*/

for ($current = 1; $current <= $pages; $current++) {
if ($current != $page) {
if ($category) {
printf(
<a href=”?category=%s&page=%d">%d\n",
$category, $current, $current
);
} else printf(
<a href=”?page=%d">%d\n",
$current, $current
);
} else printf("%d\n", $page);
}
?>[/php]

I was wondering if any one could meet me in a collaboration site and help me rewrite this? If so please email me. I would be available anytime if someone could help me. I’ve been trying to figure this out for a week now.

I tried taking a stab at it by writing a Pagination Function and including it on my news page, I feel I almost have it , but I’m having a problem trying to limit the number of news articles per page on the news section of my website.

Currently I only have 4 articles in my news section. I would like to set the number of articles shown on each page to 2 articles per page. Then when I click page 2 it will show the next two articles. So on and so on. As of now the pagination numbers show 1-4 and on each page show all 4 articles. I want this to show 1-2, and 2 articles on each page.

Sorry for the code dump. I think the problem is in my query down below in the 3rd section.

I have my pagination function setup like this:
FYI I have my database connection script stored in my header.

[php]<?php

//Pagination Function
function pagination($per_page = 2, $page = 1, $url = ‘’, $total){

    $adjacents = "2";

    $page = ($page == 0 ? 1 : $page); 
    $start = ($page - 1) * $per_page;                              
     
    $prev = $page - 1;                         
    $next = $page + 1;
    $lastpage = ceil($total/$per_page);
    $lpm1 = $lastpage - 1;
     
    $pagination = "";
    if($lastpage > 1)
    {  
        $pagination .= "<ul class='pagination'>";
                $pagination .= "<li class='details'>Page $page of $lastpage</li>";
        if ($lastpage < 7 + ($adjacents * 2))
        {  
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<li><a class='current'>$counter</a></li>";
                else
                    $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";                   
            }
        }
        elseif($lastpage > 5 + ($adjacents * 2))
        {
            if($page < 1 + ($adjacents * 2))    
            {
                for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<li><a class='current'>$counter</a></li>";
                    else
                        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";                   
                }
                $pagination.= "<li class='dot'>...</li>";
                $pagination.= "<li><a href='{$url}$lpm1'>$lpm1</a></li>";
                $pagination.= "<li><a href='{$url}$lastpage'>$lastpage</a></li>";     
            }
            elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
                $pagination.= "<li><a href='{$url}1'>1</a></li>";
                $pagination.= "<li><a href='{$url}2'>2</a></li>";
                $pagination.= "<li class='dot'>...</li>";
                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<li><a class='current'>$counter</a></li>";
                    else
                        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";                   
                }
                $pagination.= "<li class='dot'>..</li>";
                $pagination.= "<li><a href='{$url}$lpm1'>$lpm1</a></li>";
                $pagination.= "<li><a href='{$url}$lastpage'>$lastpage</a></li>";     
            }
            else
            {
                $pagination.= "<li><a href='{$url}1'>1</a></li>";
                $pagination.= "<li><a href='{$url}2'>2</a></li>";
                $pagination.= "<li class='dot'>..</li>";
                for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "<li><a class='current'>$counter</a></li>";
                    else
                        $pagination.= "<li><a href='{$url}$counter'>$counter</a></li>";                   
                }
            }
        }
         
        if ($page < $counter - 1){
            $pagination.= "<li><a href='{$url}$next'>Next</a></li>";
            $pagination.= "<li><a href='{$url}$lastpage'>Last</a></li>";
        }else{
            $pagination.= "<li><a class='current'>Next</a></li>";
            $pagination.= "<li><a class='current'>Last</a></li>";
        }
        $pagination.= "</ul>\n";     
    }          
    return $pagination;
} 		

?> [/php]

And this is how I’m calling it on my news page: I think my problem is the query on the 3rd part.

1st part

[php]<?php
$title = ‘…’;
$page_description = “…”;
$thisPage=“news”;
include_once($_SERVER[‘DOCUMENT_ROOT’] . “/header.php”);
include_once($_SERVER[‘DOCUMENT_ROOT’] . “/includes/pagination.php”);
$id = ‘id’;
$date = $_GET[‘date’];
?>[/php]

2nd part

[php]<?php
$page=1;//Default page
$limit=1;//Records per page
$start=1;//starts displaying records from 0
if(isset($_GET[‘page’]) && $_GET[‘page’]!=’’){
$page=$_GET[‘page’];
}
$start=($page-1)*$limit;

?>

<?php $sql = "SELECT id FROM `htp_news`"; $ps_count = $db->prepare($sql); $ps_count->execute(array( ':id'=>$id)); $ps_count->execute(); $rows = $ps_count->rowCount(); $sql_2 = "SELECT id FROM `htp_news` where date = :date order by id ASC LIMIT :start, :limit"; $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); $ps = $db->prepare($sql_2); $ps->execute(array( ':date'=>$_GET['date'], ':start'=>$start, ':limit'=>$limit)); $ps->execute(); while ($row = $ps->fetch(PDO::FETCH_ASSOC)) { ?> <?php } ?>[/php]

3rd part (This is where I’m getting confused on how to limit the # of articles. I’m not sure what to add to the query to limit…?)

[php]<?php
$query = $db->query("SELECT id, date, title, description FROM htp_news ORDER BY date DESC $limit ");
while ($row = $query->fetch(PDO::FETCH_ASSOC))

{
?>

  • ">
    <?=$row["title"] ?>
    <?= date("F d, Y", strtotime($row["date"])); ?>
    .articletext img{width:100%; height:auto;}<?php $string = $row["description"]; $max = 300; // or 200, or whatever if(strlen($string) > $max) { // find the last space < $max: $shorter = substr($string, 0, $max+1); $string = substr($string, 0, strrpos($shorter, ' ')).'...'; } echo $string; ?>
  • <?php } ?>[/php]

    4th part:

    [php]<?php
    echo pagination($limit,$page,‘my-site-news.php?date=’.$date.’&page=’,$rows); //call function to show pagination
    ?>[/php]

    I’m pretty desperate for some help. If someone could help me rewrite my original script that would be great.
    Or, Any guidance or help on my 2nd attempt would be greatly appreciated as well.
    Thanks!

    Post an sql dump of your database.

    Here is the sql dump:

    – phpMyAdmin SQL Dump
    – version 4.0.9
    http://www.phpmyadmin.net

    – Host: 127.0.0.1
    – Generation Time: Apr 05, 2014 at 02:51 AM
    – Server version: 5.5.34
    – PHP Version: 5.4.22

    SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
    SET time_zone = “+00:00”;


    – Database: htp



    – Table structure for table htp_news

    CREATE TABLE IF NOT EXISTS htp_news (
    id int(4) NOT NULL AUTO_INCREMENT,
    date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    title varchar(256) NOT NULL,
    description varchar(15000) NOT NULL,
    PRIMARY KEY (id)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=104 ;


    – Dumping data for table htp_news

    INSERT INTO htp_news (id, date, title, description) VALUES
    (85, ‘2013-12-19 15:26:11’, ‘Mireille Senecharle’, ‘

    \r\n

    During our time in Haiti at the Foyer Divine School in Belanger,  we had the pleasure to speak with a local mother, Mireille Senecharle.

    \r\n

    Mireille Senecharle wanted to speak to us about how the pack has had a great impact on her family. She said that before the water packs, her children could not bring water back to their house do to the weight of the Jerry Cans they were currently using.

    \r\n

    Now that they have the Hydro-TransPak the children are now able to contribute to the family by bringing water home on a daily basis and do so without being told. Mireille’s eldest daughter also teaches her younger siblings on how to use the Hydro-TransPak to collect water, wear the pack correctly and transport the water home. Mireille’s only request was that she would like to see a water pack that would be large enough for adults to wear and possibly hold more water.

    \r\n

    You can view the interview here.

    ’),
    (86, ‘2013-12-19 17:04:52’, 'Foyer Divine School ', ‘

    \r\n

    Our first day out in Haiti we meet with the team from Living Water International. Our guide Ted took us to the Foyer Divine School in Belanger, Haiti.

    \r\n

    We first sat down in the classroom of an estimated 32 students and a few teachers and parents. We had a brief Q & A with the children. We first wanted to know how many of the children had one of the Hydro-TransPak’‘s and asked everyone that had a pack to hold theirs up so we could see. Almost every child held up a pack. We then began a discussion of what they liked about the packs. What we found out was that almost all the children used the packs on a daily basis. We did find out however that many of the children were using the pack incorrectly. In which we demonstrated to them on how to use the packs properly.

    \r\n

    \r\n

    After our Q & A session the children demonstrated to us at the well how they used the bags to collect the water. Now most of the children understood how to use the bags correctly.

    \r\n

    \r\n


    We did however have to reiterate the process again to a few students that did not understand the first time.

    \r\n

    We were very grateful for our time spent with the teachers, parents and children at the school and it was a great learning experience for our team.

    ’),
    (102, ‘2014-04-02 16:04:52’, ‘Test post 1’, ‘

    \r\n

    Our first day out in Haiti we meet with the team from Living Water International. Our guide Ted took us to the Foyer Divine School in Belanger, Haiti.

    \r\n

    We first sat down in the classroom of an estimated 32 students and a few teachers and parents. We had a brief Q & A with the children. We first wanted to know how many of the children had one of the Hydro-TransPak’‘s and asked everyone that had a pack to hold theirs up so we could see. Almost every child held up a pack. We then began a discussion of what they liked about the packs. What we found out was that almost all the children used the packs on a daily basis. We did find out however that many of the children were using the pack incorrectly. In which we demonstrated to them on how to use the packs properly.

    \r\n

    \r\n

    After our Q & A session the children demonstrated to us at the well how they used the bags to collect the water. Now most of the children understood how to use the bags correctly.

    \r\n

    \r\n


    We did however have to reiterate the process again to a few students that did not understand the first time.

    \r\n

    We were very grateful for our time spent with the teachers, parents and children at the school and it was a great learning experience for our team.

    ’),
    (103, ‘2014-03-11 14:26:11’, ‘TEST post 2’, ‘

    \r\n

    During our time in Haiti at the Foyer Divine School in Belanger,  we had the pleasure to speak with a local mother, Mireille Senecharle.

    \r\n

    Mireille Senecharle wanted to speak to us about how the pack has had a great impact on her family. She said that before the water packs, her children could not bring water back to their house do to the weight of the Jerry Cans they were currently using.

    \r\n

    Now that they have the Hydro-TransPak the children are now able to contribute to the family by bringing water home on a daily basis and do so without being told. Mireille’s eldest daughter also teaches her younger siblings on how to use the Hydro-TransPak to collect water, wear the pack correctly and transport the water home. Mireille’s only request was that she would like to see a water pack that would be large enough for adults to wear and possibly hold more water.

    \r\n

    You can view the interview here.

    ’);

    This should get you going…

    [php]

    PDO Pagination <!-- div.pagination {text-align:center;margin:3px;padding:3px;} div.pagination a {margin-right:2px;border:1px solid #2C2C2C;text-decoration:none;color:#fff;background:#2C2C2C;padding:2px 5px;} div.pagination a:hover,div.pagination a:active {border:1px solid #AAD83E;color:#FFF;background:#AAD83E;} div.pagination span.current {margin-right:2px;border:1px solid #AAD83E;font-weight:700;background:#AAD83E;color:#FFF;padding:2px 5px;} div.pagination span.disabled {margin-right:2px;border:1px solid #f3f3f3;color:#ccc;padding:2px 5px;}

    .datatable {border:none;width:100%;color:#666;margin:0;padding:0;}
    .datatable th {font:bold 11px Verdana, Arial;color:#FFFFFF;border-right:1px solid #C1DAD7;border-bottom:1px solid #C1DAD7;border-top:1px solid #C1DAD7;letter-spacing:1px;text-transform:uppercase;text-align:left;background:#99CC33 repeat;padding:2px 2px 2px 3px;}
    .datatable td {border-right:1px solid #CCC;border-bottom:1px solid #CCC;border-top:1px solid #CCC;border-left:1px solid #CCC;font:12px Verdana, Arial;color:#333;padding:2px 2px 2px 3px;}
    –>

    <?php

    $hostname = ‘localhost’;
    $username = ‘root’;
    $password = ‘’;

    try
    {
    $dbh = new PDO(“mysql:host=$hostname;dbname=htp”, $username, $password);
    }
    catch (PDOException $e)
    {
    echo $e->getMessage();
    }
    // No. of adjacent pages shown on each side
    $adjacents = 2;

    $stmt = $dbh->prepare(“SELECT * FROM htp_news”);
    $stmt->execute();

    $records = $stmt->rowCount();
    $targetpage = “index.php”;
    $limit = 2;
    $page = $_GET[‘page’];
    if ($page)
    $start = ($page - 1) * $limit;
    else
    $start = 0;
    $stmt = $dbh->prepare(“SELECT * FROM htp_news LIMIT $start, $limit”);

    $stmt ->execute();
    $rows = $stmt ->fetchAll();

    if ($page == 0)
    $page = 1;

    $prev = $page - 1;

    $next = $page + 1;

    $lastpage = ceil($records / $limit);

    $lpm1 = $lastpage - 1;

    $pagination = “”;
    if ($lastpage > 1)
    {
    $pagination .= “

    ”;
    if ($page > 1)
        $pagination .= "<a href='$targetpage?page=$prev'>Previous</a>";
    else
        $pagination .= "<span class='disabled'>Previous</span>";
    
    if ($lastpage < 7 + ($adjacents * 2))
        {
        for ($counter = 1; $counter <= $lastpage; $counter++)
            {
            if ($counter == $page)
                $pagination .= "<span class='current'>$counter</span>";
            else
                $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
            }
        }
    elseif ($lastpage > 5 + ($adjacents * 2))
        {
        
        if ($page < 1 + ($adjacents * 2))
            {
            for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                if ($counter == $page)
                    $pagination .= "<span class='current'>$counter</span>";
                else
                    $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
                }
            $pagination .= "...";
            $pagination .= "<a href='$targetpage?page=$lpm1'>$lpm1</a>";
            $pagination .= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
            }
        
        elseif ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
            $pagination .= "<a href='$targetpage?page=1'>1</a>";
            $pagination .= "<a href='$targetpage?page=2'>2</a>";
            $pagination .= "...";
            for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                if ($counter == $page)
                    $pagination .= "<span class='current'>$counter</span>";
                else
                    $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
                }
            $pagination .= "...";
            $pagination .= "<a href='$targetpage?page=$lpm1'>$lpm1</a>";
            $pagination .= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
            }
        
        else
            {
            $pagination .= "<a href='$targetpage?page=1'>1</a>";
            $pagination .= "<a href='$targetpage?page=2'>2</a>";
            $pagination .= "...";
            for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                {
                if ($counter == $page)
                    $pagination .= "<span class='current'>$counter</span>";
                else
                    $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
                }
            }
        }
    
    
    if ($page < $counter - 1)
        $pagination .= "<a href='$targetpage?page=$next'>Next</a>";
    else
        $pagination .= "<span class='disabled'>Next</span>";
    $pagination .= "</div>\n";
    }
    

    echo “

    ”;
    echo “”;

    foreach ($rows as $r)
    {
    echo “

    ”;
    echo “”;
    echo “”;
    echo “”;
    echo “”;
    echo “”;
    }
    echo “
    ID Date Title Description
    ” . $r[0] . “” . $r[1] . “” . $r[2] . “” . $r[3] . “
    ”;

    echo $pagination;
    ?>

    [/php]

    Kevin thank you so much, I really appreciate it. This will definitely get me going!!!

    I’m pretty new to PHP and PDO. Just curious, is there a book or tutorial series that you would recommend that will teach me the file / folder structure in setting up a website using PDO or help me grasp it better. Please don’t give me a link to the manual, ::slight_smile: I’ve been through it a few times and it’s hard for me to understand.

    Seems like most of the books I have teach old outdated practices, which is strange to me because I go on the forums and everyone is telling me I got to switch to PDO or MySQLi because MySQL is becoming depreciated, but PDO and MySQLi have been around for years and my PHP books are fairly new 2011-2013. Anyways, any suggestions are welcome.

    Thank you again for helping me out. You are very kind. Much appreciated!

    I'm pretty new to PHP and PDO. Just curious, is there a book or tutorial series that you would recommend that will teach me the file / folder structure in setting up a website using PDO or help me grasp it better.
    I would reccommend the "Kevin Rubio Live One On One Training Series" (Hee, hee, shameless plug). An important thing to learn is "Seperation of Concerns". [url=http://en.wikipedia.org/wiki/Separation_of_concerns]http://en.wikipedia.org/wiki/Separation_of_concerns[/url]
    Please don't give me a link to the manual, ::) I've been through it a few times and it's hard for me to understand.
    Yeah, the manual pretty much sucks. Even I can hardly understand it.
    Seems like most of the books I have teach old outdated practices, which is strange to me because I go on the forums and everyone is telling me I got to switch to PDO or MySQLi because MySQL is becoming depreciated, but PDO and MySQLi have been around for years and my PHP books are fairly new 2011-2013.]Seems like most of the books I have teach old outdated practices, which is strange to me because I go on the forums and everyone is telling me I got to switch to PDO or MySQLi because MySQL is becoming depreciated, but PDO and MySQLi have been around for years and my PHP books are fairly new 2011-2013.

    Yeah, outdated info is all over the place. I am always posting on old tutorials to remove or update their code. Mysql is ALREADY deprecated.

    Thank you again for helping me out. You are very kind. Much appreciated!
    Your very welcome!

    Thanks for the advice about Seperation of Concerns.

    I would reccommend the "Kevin Rubio Live One On One Training Series"

    Is this a real series or were you just messing around? If you have a book or video tutorials please send link.

    Thanks

    No, not messing around. I do live training by phone or skype and a direct connection to your machine.

    Ahh good to know. I might take you up on that in the near future. Email me your rate if you don’t mind.

    The PHP manual is actually pretty damn good, might just be compared to what else is out there.

    PHP/PDO has no real demands for spesific folder or code structure. You do get a thumbs up for beeing interested in best practices though, so have a look into the coding guidelines of big frameworks, like the Zend Coding Standards. You should also try to be PSR-compliant, once you start with classes and autoloading this makes your life a lot easier.

    Regarding pagination I usually just do something like this:

    [php]$start = !empty($_GET[‘start’]) ? (int) $_GET[‘start’] : 0;
    $limit = !empty($_GET[‘limit’]) ? (int) $_GET[‘limit’] : 10;
    $order = !empty($_GET[‘order’]) && $_GET[‘order’] == ‘asc’ ? $_GET[‘order’] : ‘desc’;

    $sth = $dbh->(“SELECT id, title, intro FROM post ORDER BY created $order LIMIT $start, $limit”);
    $posts = $sth->execute();[/php]

    Note that order, limit params, database, table and column names are not possible to bind as parameters to the query. In these cases you are best off hardcoding tables and making absolutely 100% sure the rest is what you think they are. One slip and you’re done.

    Which brings us to the next point in the list. You should always consider your site hackable, how would your sensitive data storage hold up (passwords, etc)?

    Hey Kevin I tried to incorporate this script into my site and the only issue I’m having is displaying more post / articles on my page by changing the limit variable. It changes the pagination results, but I’m only getting 1 post / article to show up on each page. I modified it slightly to include my styling, could you take a look and maybe see where I went wrong? Thank You.

    [php]<?php
    // No. of adjacent pages shown on each side
    $adjacents = 2;

    $stmt = $db->prepare(“SELECT id, date, title, description FROM htp_news”);
    $stmt->execute();

    $records = $stmt->rowCount();
    $targetpage = basename($_SERVER[‘PHP_SELF’]);
    $limit = 4;// !!!When I change the limit number it changes the pagination results, but does not add more articles to the page…!!!
    $page = isset($_GET[‘page’])? $_GET[‘page’] : 1;
    if ($page)
    $start = ($page - 1) * $limit;
    else
    $start = 0;
    $stmt = $db->prepare(“SELECT * FROM htp_news ORDER BY id DESC LIMIT $start, $limit”);

    $stmt ->execute();
    $rows = $stmt ->fetchAll();

    if ($page == 0)
    $page = 1;

    $prev = $page - 1;

    $next = $page + 1;

    $lastpage = ceil($records / $limit);

    $lpm1 = $lastpage - 1;

    $pagination = “”;
    if ($lastpage > 1)
    {
    $pagination .= “

    ”;
      if ($page > 1)
          $pagination .= "<a href='$targetpage?page=1'>First</a>";
      else
          $pagination .= "<span class='disabled'>First</span>";
      
      
      if ($page > 1)
          $pagination .= "<a href='$targetpage?page=$prev'>&lsaquo; &lsaquo;</a>";
      else
          $pagination .= "<span class='disabled'>&lsaquo; &lsaquo;</span>";
      
      if ($lastpage < 7 + ($adjacents * 2))
          {
          for ($counter = 1; $counter <= $lastpage; $counter++)
              {
              if ($counter == $page)
                  $pagination .= "<span class='current'>$counter</span>";
              else
                  $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
              }
          }
      elseif ($lastpage > 5 + ($adjacents * 2))
          {
          
          if ($page < 1 + ($adjacents * 2))
              {
              for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                  {
                  if ($counter == $page)
                      $pagination .= "<span class='current'>$counter</span>";
                  else
                      $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
                  }
              $pagination .= "...";
              $pagination .= "<a href='$targetpage?page=$lpm1'>$lpm1</a>";
             $pagination .= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
             }
         
         elseif ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
             {
             $pagination .= "<a href='$targetpage?page=1'>1</a>";
             $pagination .= "<a href='$targetpage?page=2'>2</a>";
             $pagination .= "...";
             for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                 {
                 if ($counter == $page)
                     $pagination .= "<span class='current'>$counter</span>";
                 else
                     $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
                 }
             $pagination .= "...";
             $pagination .= "<a href='$targetpage?page=$lpm1'>$lpm1</a>";
             $pagination .= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
             }
         
         else
             {
             $pagination .= "<a href='$targetpage?page=1'>1</a>";
             $pagination .= "<a href='$targetpage?page=2'>2</a>";
             $pagination .= "...";
             for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                 {
                 if ($counter == $page)
                     $pagination .= "<span class='current'>$counter</span>";
                 else
                     $pagination .= "<a href='$targetpage?page=$counter'>$counter</a>";
                 }
             }
         }
     
     
     if ($page < $counter - 1)
         $pagination .= "<a href='$targetpage?page=$next'>&rsaquo; &rsaquo;</a>";
     else
         $pagination .= "<span class='disabled'>&rsaquo; &rsaquo;</span>";
     
     
     if ($page < $counter - 1)
         $pagination .= "<a href='$targetpage?page=$lastpage'>Last</a>";
     else
         $pagination .= "<span class='disabled'>Last</span>";
     $pagination .= "</div>\n";
    

    }

    //echo “

    ”;
    //echo “ID,Date,Title,Description”;

    foreach ($rows as $r)
    {
    //echo “

    ”;
    //echo $r[1];
    //echo $r[1];
    //echo $r[2];
    //echo $r[3];
    //echo “”;
    }
    //echo “
    ”;

    ?>

  • <?= $r[2] ?>
    <?= date("F d, Y", strtotime($r[1])); ?>
    .articletext img{width:100%; height:auto;}<?php $string = $r[3]; $max = 300; // or 200, or whatever if(strlen($string) > $max) { // find the last space < $max: $shorter = substr($string, 0, $max+1); $string = substr($string, 0, strrpos($shorter, ' ')).'...'; } echo $string; ?>
  • <?php echo $pagination;?>

    [/php]

    Go back to the original code and change the number of records display. Test it and make sure it works. Then… make your custom changes slowly testing in between changes.

    Theeeeen… come back here and tell me what you did wrong the first time.

    I did, it all works fine on the original script up to this point.

    [php] //echo “

    ”;
    //echo “ID,Date,Title,Description”;

    foreach ($rows as $r)
    {
    //echo “

    ”;
    //echo $r[1];
    //echo $r[1];
    //echo $r[2];
    //echo $r[3];
    //echo “”;
    }
    //echo “
    ”;

    ?>

  • <?= $r[2] ?>
    <?= date("F d, Y", strtotime($r[1])); ?>
    .articletext img{width:100%; height:auto;}<?php $string = $r[3]; $max = 300; // or 200, or whatever if(strlen($string) > $max) { // find the last space < $max: $shorter = substr($string, 0, $max+1); $string = substr($string, 0, strrpos($shorter, ' ')).'...'; } echo $string; ?>
    Continue Reading
  • [/php]

    To get my original styling do I need to add everything in my list in the php code itself, between the foreach brackets and echo out each line / article tag / div tag? I think that’s the problem but not sure how to convert all that html into php.

    Here is a good example of my problem with the manual. This is a link to the filters examples, yet there is not a single example of using the optional flags with the filters.

    http://www.php.net/manual/en/filter.examples.validation.php

    I think they’re kinda dependant on the community adding stuff to the manual. But there are some examples

    options
    Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callable type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</blockquote>
    

    [php]<?php
    // for filters that accept options, use this format
    $options = array(
    ‘options’ => array(
    ‘default’ => 3, // value to return if the filter fails
    // other options here
    ‘min_range’ => 0
    ),
    ‘flags’ => FILTER_FLAG_ALLOW_OCTAL,
    );
    $var = filter_var(‘0755’, FILTER_VALIDATE_INT, $options);

    // for filter that only accept flags, you can pass them directly
    $var = filter_var(‘oops’, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

    // for filter that only accept flags, you can also pass as an array
    $var = filter_var(‘oops’, FILTER_VALIDATE_BOOLEAN,
    array(‘flags’ => FILTER_NULL_ON_FAILURE));

    // callback validate filter
    function foo($value)
    {
    // Expected format: Surname, GivenNames
    if (strpos($value, ", “) === false) return false;
    list($surname, $givennames) = explode(”, ", $value, 2);
    $empty = (empty($surname) || empty($givennames));
    $notstrings = (!is_string($surname) || !is_string($givennames));
    if ($empty || $notstrings) {
    return false;
    } else {
    return $value;
    }
    }
    $var = filter_var(‘Doe, Jane Sue’, FILTER_CALLBACK, array(‘options’ => ‘foo’));[/php]
    http://www.php.net/manual/en/function.filter-var.php

    Okay so I do have to convert my html to echoed out php code.
    I tested out with only the Titles and the $limit count was working perfect.

    So for this:<article class="box white-bg mb-25">
    I did this: [php]echo “”;[/php]

    For this:<div class="notices-title"><?= $r[title] ?></div>
    I did this: [php]echo “

    $r[title]
    ”;[/php]

    This is where I can’t figure out how to covert the code and keep the exsiting php I have while coverting and echoing out.

    Need help converting the following to php:

    1. <div class="newsdate" style="margin: 10px 0 !important;"><?= date("F d, Y", strtotime($r[date])); ?></div>
    2. <div class="articletext"><style>.articletext img{width:100%; height:auto;}</style><?php $string = $r[description]; $max = 300; // or 200, or whatever if(strlen($string) > $max) { // find the last space < $max: $shorter = substr($string, 0, $max+1); $string = substr($string, 0, strrpos($shorter, ' ')).'...'; } echo $string; ?></div>

    3. <div class="btn small green white-tx"><a href="http://<?php echo $_SERVER['SERVER_NAME']; ?>/htp-news.php?id=<?=$r[id] ?>">Continue Reading</a></div>

    Any help would be appreciated.

    Okay all is working great now, and I can adjust the limits of articles that appear on the page.

    I just had to modify the foreach statement like so:

    [php]<?php foreach ($rows as $r) : ?>

  • <?= $r[2] ?>
    <?= date("F d, Y", strtotime($r[1])); ?>
    .articletext img{width:100%; height:auto;}<?php $string = $r[3]; $max = 300; // or 200, or whatever if(strlen($string) > $max) { // find the last space < $max: $shorter = substr($string, 0, $max+1); $string = substr($string, 0, strrpos($shorter, ' ')).'...'; } echo $string; ?>
    Continue Reading
  • <?php endforeach?> [/php]

    I didn’t realize I could do an endforeach.
    Thanks again for all the help.

    Very good. You can also do if/endif. Nice when you figure things out on your own. :smiley:

    Another handy function is heredoc.

    [php]echo <<<EOT
    My name is “$name”. I am printing some $foo->foo.
    Now, I am printing some {$foo->bar[1]}.
    This should print a capital ‘A’: \x41
    EOT;
    ?>[/php]

    Sponsor our Newsletter | Privacy Policy | Terms of Service