Converting old pagination mysql_query php to PDO - php

I'm trying to switch over to using PDO. I have create a news section on my website.
My database connection is included in my header
I'm currently using this to create the pagination, but need help adding my post
to the $data = array("Hey","Hello","Good-Bye"); As of now Hey, Hello and Good-Bye are the only items working with the pagination.
Can someone hep me get this result: $data = array("add my post here")
Here is my code: My database connection is in the header section.
<?php
class Pagination{
var $data;
function Paginate($values,$per_page){
$total_values = count($values);
if(isset($_GET['page']))
{
$current_page = $_GET['page'];
}
else
{
$current_page = 1;
}
$counts = ceil($total_values / $per_page);
$param1 = ($current_page - 1) * $per_page;
$this->data = array_slice($values,$param1,$per_page);
for ($x=1; $x<= $counts; $x++)
{
$numbers[] = $x;
}
return $numbers;
}
function fetchResult(){
$resultsValues = $this->data;
return $resultsValues;
}
}
?>
I'm assuming that I need the <ul class="notices"> - </ul>(shown below) IN PLACE OF THE $data = array("Hey","Hello","Good-Bye"); DOWN BELOW
Not sure how to do this though?
<ul class="notices">
<?php
$query = $db->query("SELECT id, date, title, description FROM htp_news");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
?>
<li data-id="id-<?=$row["id"] ?>">
<article class="box white-bg mb-25">
<div class="notices-title"><?=$row["title"] ?></div>
<div class="newsdate" style="margin: 10px 0 !important;"><?= date("F d, Y", strtotime($row["date"])); ?></div>
<div class="articletext"><style>.articletext img{width:100%; height:auto;}</style><?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;
?></div>
<div class="btn small green white-tx">Continue Reading</div>
</article>
</li>
<?php
}
?>
</ul>
<div class="grid_8">
<div class="paginationwrap" align="center">
<!--This is where the pagination numbers are being generated-->
<?php
$pag = new Pagination();
$data = array("Hey","Hello","Good-Bye");//This is where I'm getting confused..?
$numbers = $pag->Paginate($data,1);
$result = $pag->fetchResult();
foreach($result as $r)
{
echo '<div>'.$r.'</div>';
}
foreach($numbers as $num)
{
echo''.$num.'';
}
?>
Any help would be appreciated. Thank you.

Don't know why you need it, but to avoid duplication of code and javascript, you could do this like that, and then you have your data inside $inside_ul variable.
<?php
$query = $db->query("SELECT id, date, title, description FROM htp_news");
$inside_ul = '';
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$inside_ul .= '
<li data-id="id-'.$row["id"].'">
<article class="box white-bg mb-25">
<div class="notices-title">'.$row["title"].'</div>
<div class="newsdate" style="margin: 10px 0 !important;">'.date("F d, Y", strtotime($row["date"])).'</div>
<div class="articletext"><style>.articletext img{width:100%; height:auto;}</style>
';
$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, ' ')).'...';
}
$inside_ul .= $string.'</div>
<div class="btn small green white-tx">
Continue Reading
</div>
</article>
</li>
';
}
?>
<ul class="notices"><?= $inside_ul; ?></ul>

Related

Wordpress: get_post_field() throws error like it's trying to redefine a function

I have a function called getNews().
I call getNews() like this:
<div class="wrapper" id="blog">
<div class="blogPosts">
<?PHP getNews($postPerPage, 0, $theme_link, $pageNum); ?>
</div>
</div>
The function works until it tries to get the article text from wordpress using get_post_field().
function getNews($numPosts, $offset, $theme_link, $pageNum) {
$offset = $numPosts * $pageNum;
$recent_args = array('numberposts' => $numPosts, 'offset' => $offset,);
$articles = wp_get_recent_posts($recent_args);
foreach($articles as $article){
$article_id = $article['ID'];
...
echo $article_text = get_post_field('post_content', $article_id);
...
}
}
When I run this, I get the error saying Fatal error: Cannot redeclare getNews() (previously declared in /homepages/30/d545089862/htdocs/VintageTroubleMusic/wp-content/plugins/enhanced-text-widget/enhanced-text-widget.php(57)
For some reason, it's running my loop twice.
Any advice?
EDIT
I'm including the full code here: This is written inside of an "Enhanced Text widget" inside of a page.
<?PHP
$theme_link = "/wp-content/themes/thestory-child/";
$pageNum = $_GET['pa'];
$postPerPage = 27;
$qry_numPosts = mysql_query("SELECT * FROM Ykcfdlqhposts WHERE post_status = 'publish' AND post_type = 'post'") or die(mysql_error());
$numPosts = mysql_num_rows($qry_numPosts);
$numPages = ceil($numPosts/$postPerPage) . " pages";
if(!$pageNum){
$pageNum = 0;
}
?>
<!-- START OF THE BODY HERE -->
<h3 class="widget-title" style="float:left;">Headlines</h3>
<div class="wrapper" id="paginate1">
<?PHP paginate($numPosts, $numPages); ?>
</div>
<div class="wrapper" id="blog">
<div class="blogPosts">
<?PHP getNews($postPerPage, 0, $theme_link, $pageNum); ?>
</div>
</div>
<div class="wrapper" id="paginate2">
<?PHP paginate($numPosts, $numPages); ?>
</div>
And inside of the functions.php page
function getNews($numPosts, $offset, $theme_link, $pageNum) {
$offset = $numPosts * $pageNum;
$recent_args = array('numberposts' => $numPosts, 'offset' => $offset,);
$articles = wp_get_recent_posts($recent_args);
foreach($articles as $article){
$article_id = $article['ID'];
$article_link = get_permalink($article_id);
$article_length = 350;
$article_background = get_the_post_thumbnail($article_id);
$article_title = get_post_meta( $article_id, 'short_title', true );
$article_text = "test";
$article_text = get_post_field('post_content', $article_id);
//$article_text = get_post_field('post_content', $article_id);
//$article_text = strip_tags($article_text);
//$article_text_length = strlen($article_text);
/*
if($article_text_length >= $article_length) {
$article_text_pos = strpos($article_text, " ", $article_length);
$article_text = substr($article_text, 0, $article_text_pos)."... ";
}
*/
?>
<div class="article">
<?PHP //Get the article image
if (!$article_background) {
$rand = rand(1, 5);
$img = $theme_link . "images/img" . $rand . ".jpg";
} else {
$img = explode('src="', $article_background);
$img = explode(".jpg", $img[1]);
$img = $img[0] . ".jpg";
}?>
<a href="<?= $article_link; ?>">
<div class="article__image" style="background-image: url('<?= $img; ?>');"></div>
<div class="article__title"><?= $article_title; ?></div>
</a>
<div class="article__details">
<div class="article-text">
<?= $article_text; ?>
</div>
READ MORE
</div>
</div>
<? }
}
function paginate($numPosts, $numPages) {
?>
<div class="page">
<span>Page:</span><?PHP
$i = 0;
while($i < $numPages){
$i++;
if($i == $pageNum){
echo '<span style="background-color:transparent; text-decoration:underline; color:white; cursor:default;">'.$i.'</span>';
} else {
echo "<a href='?pa=".$i."'><span>".$i."</span></a>";
}
}
?>
</div>
<?
}

Per Page Results PHP

I currently pull through data from a soap feed using this PHP, is there anyway for me to have the results ordered from high to low using the data from $weekrent?
Any help would be great! Here is my PHP code:
<?php
$wsdl = "http://portal.letmc.com/PropertySearchService.asmx?WSDL";
$client = new SoapClient($wsdl, array ("trace"=>1, "exceptions"=>0));
$strClientID = "{0050-e58a-cd32-3771}";
$strBranchID = "{0004-e58a-cd32-399e}";
$strAreaID = $_GET['area'];
$nMaxResults = $_GET['perpage'];
$nRentMinimum = $_GET['minrent'];
$nRentMaximum = $_GET['maxrent'];
$nMaximumTenants = $_GET['numtennants'];
$parameters = array( "strClientID"=>$strClientID,
"strBranchID"=>$strBranchID,
"strAreaID"=>$strAreaID,
"nMaxResults"=>$nMaxResults,
"nRentMinimum"=>$nRentMinimum,
"nRentMaximum"=>$nRentMaximum,
"nMaximumTenants"=>$nMaximumTenants
);
$values = $client->SearchProperties($parameters);
if(!is_array($values->SearchPropertiesResult->PropertyInfo))
{
$values->SearchPropertiesResult->PropertyInfo = array($values->SearchPropertiesResult->PropertyInfo);
}
if($values != '')
{
foreach ($values->SearchPropertiesResult->PropertyInfo as $message)
{
$uglyid = $message->ID;
$id = $message->FriendlyID;
$mainphoto = $message->MainPhoto->PhotoUrl;
$furnished = $message->Furnished;
$addressline1 = $message->Address1;
$rooms = $message->MaxTenants;
$rent = $message->Rent;
$description = $message->Description;
$isletagreed = $message->IsLetAgreed;
$facilities = $message->Facilities->FacilityInfo;
$photos = $message->Photos->PhotoInfo;
$roomsinfo = $message->Rooms->RoomInfo;
$facilitiesstring = serialize($facilities);
$extractnumbers = ereg_replace("[^0-9]", "", $rent);
$monthrent = ($extractnumbers) / $rooms;
$monthrentrounded = number_format(($monthrent/100),2);
$weekrent = ($monthrentrounded) * 12 / 52;
$weekrentrounded = floor($weekrent * 100) / 100;
$roomsinfojson = json_encode($roomsinfo);
$facilitiesjson = json_encode($facilities);
$roomsinfodouble = (substr_count(strip_tags($roomsinfojson),"Double"));
$roomsinfosingle = (substr_count(strip_tags($roomsinfojson),"Single"));
$roomsinfobathroom = (substr_count(strip_tags($roomsinfojson),"Bathroom"));
$roomsinfoshower = (substr_count(strip_tags($roomsinfojson),"Shower"));
$facilitiesparking = (substr_count(strip_tags($facilitiesjson),"Parking"));
$facilitiesgarden = (substr_count(strip_tags($facilitiesjson),"Garden"));
$totalbathrooms = $roomsinfobathroom + $roomsinfoshower;
$totalimages = count($photos);
echo '
<div class="col-property-box col-property-box-1-3">
<div class="owl-property-box">';
$i=0; foreach ($photos as $data) { if($i==4) break; echo '<div class="property-grid-box-picture" style="background: url('. $data->PhotoUrl .') center center;"></div>'; $i++; };
echo '</div>
<div class="property-grid-box">
'. $addressline1 .'
<p class="property-grid-box-text">'. limit_words($description,19) .'...</p>
<div class="property-grid-box-price">
<div class="section group">
<div class="col col-property-box-1-2 property-grid-box-price-border-right">
<div class="property-grid-box-price-top">£'. $weekrentrounded.'pp</div> <div class="property-grid-box-price-under">Weekly</div>
</div>
<div class="col col-property-box-1-2">
<div class="property-grid-box-price-top">£'. $monthrentrounded .'pp</div> <div class="property-grid-box-price-under">Monthly</div>
</div>
</div>
</div>
<div class="property-grid-box-icon-box">
<div class="section group">
<div class="col col-1-3-border no-left-border">
<span class="property-grid-box-number-icon"><center><i class="fa fa-bed"></i></center><div class="property-grid-box-number-text">'. $rooms .'</div></span>
</div>
<div class="col col-1-3-border">
<span class="property-grid-box-number-icon"><center><i class="flaticon-shower5"></i></center><div class="property-grid-box-number-text">'. $totalbathrooms .'</div></span>
</div>
<div class="col col-1-3-border">
<span class="property-grid-box-number-icon"><center><i class="flaticon-beds12"></i></center><div class="property-grid-box-number-text">'. $totalimages .'</div></span>
</div>
</div>
</div>
</div>
</div>
';
}
}
function limit_words($string, $word_limit)
{
$words = explode(" ",$string);
return implode(" ",array_splice($words,0,$word_limit));
}
?>
you can use usort function .. so you get the sorted result
Read more on php
You can put your messages data to temporary array along with calculated weekrent and then sort desc by weekrent value with usort
if($values != '')
{
$arrayForSort = array();
foreach ($values->SearchPropertiesResult->PropertyInfo as $message) {
$rent = $message->Rent;
$rooms = $message->MaxTenants;
$extractnumbers = ereg_replace("[^0-9]", "", $rent);
$monthrent = ($extractnumbers) / $rooms;
$monthrentrounded = number_format(($monthrent/100),2);
$weekrent = ($monthrentrounded) * 12 / 52;
$arrayForSort[] = array('weekrent' => $weekrent, 'message' => $message);
}
usort($arrayForSort, function($a, $b) {
if ($a['weekrent'] == $b['weekrent']) {
return 0;
}
return ($a['weekrent'] > $b['weekrent']) ? -1 : 1;
});
foreach ($arrayForSort as $item)
{
$message = $item['message'];
// Your code here to proper process the message ...

How can i change the year from the calendar when the months value passes december?

I'm building a calendar - I'm making the buttons to change the month and the year.
Every time that the button to go forward is clicked, the variable that contains the months, receives more 1 value.
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); //the ID contains the months
$next= $id + 1; //forward button
if($id < 12){
}else{
$id = 1; //puts the id variable back to 1 again
$next = $id;
}
Button code:
<button>Next</button>
Calling the function:
echo get_date($id,2014);
Now here's the problem: I'm having some problems changing the year when the id reaches december(12).
I tried this:
$years = date('Y');
$back = $id - 1;
$next= $id + 1;
if($id < 12){
}else{
$id = 1;
$next= $id;
$years++;
}
And I called the function:
echo get_date($id,$years);
get_date function:
<?php function get_date($month, $year){
switch ($month) {
case "1":
$ex_month = 'January';
break;
default:
$ex_month = 'January';
}
?>
<div id="calendar-wrap">
<div class="month-selection"><span><?= $ex_month . ' ' . $year; ?></span></div>
<<</td>
</div>
<div class="weeks">
<?php $weeks = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');?>
<div class="weeks-begin"><span><?= $weeks[0]; ?></span></div>
<div><span><?= $weeks[1]; ?></span></div>
<div><span><?= $weeks[2]; ?></span></div>
<div><span><?= $weeks[3]; ?></span></div>
<div><span><?= $weeks[4]; ?></span></div>
<div><span><?= $weeks[5]; ?></span></div>
<div><span><?= $weeks[6]; ?></span></div>
<?php
$day = date('d');
$running_day = date('w',mktime(0,0,0,$month,0,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
?>
</div>
<br>
<div class="c-col-1">
<?php
for($x = 0; $x < $running_day; $x++):
?>
<div class="c-empty"></div>
<?php
endfor;
?>
<?php for($list_day = 1; $list_day <= $days_in_month; $list_day++):
if($list_day == $day){
$div = '<div style="background: red;">';
}else{
$div = '<div>';
}
?>
<?= $div ?><span> <?= $list_day ?> </span><span class="resp-week"></span></div>
<?php
endfor;
?>
</div>
</div>
<?php }
?>
i already did it, here the solution:
I created a new parameter to get the year.
<?php }
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$get_year = preg_replace('#[^0-9]#i', '', $_GET['year']);
$teste = 1;
$back = $id - 1;
$next= $id + 1;
if($id < 12){
}else{
++$teste;
++$get_year;
$id = 1;
$next= $id;
}
?>
<button class="offersbtn">Next</button>
<?php
echo get_date($id,$get_year);
?>

Best method to add pagination to a gallery

I have clients website that is getting overloaded with images in his gallery. I was wondering if I could get some advice and see what you guys/girls think would be the best way to handle this current situation I'm in.
http://www.richsdockcompany.com/Gallery.php
This gallery is created by php and mysql. I would like to set a limit to 12 images then it would switch to a different page(s), but it can't refresh the page or else the gallery will reset.
Current Code For Gallery
<?php
include_once "header.php";
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$images = mysql_query("SELECT * FROM images");
while ($image=mysql_fetch_assoc($images))
?>
<div id="Wrap">
<div class="Titles"><h2 style="font-size:36px;">Rich's Dock Company Image Gallery</h2></div><br />
<hr />
<div id="PhotoBoxWrap">
<!--======START GALLERY======-->
<div class="row">
<div class="column grid_12">
<div class="row">
<div class="column grid_12">
<!-- start Filter categories -->
<ul id="filter">
<li class="active">All</li>
<li>Dock Builders On Shore</li>
<li>Commercial Docks</li>
<li>Residential Docks</li>
<li>Dock Repairs & Additions</li>
<li>Barge Life</li>
</ul>
<!-- End Filter categories -->
</div>
</div>
<!-- Divider -->
<div class="row">
<div class="column grid_12">
<div class="clear"></div>
<div class="divider spacer5"></div>
</div>
</div>
<!-- End divider -->
<div class="row">
<ul id="stage" class="portfolio-4column">
<?php
$images = mysql_query("SELECT * FROM images ORDER BY id DESC");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">
<div class="column grid_3 gallerybox">
<a class="fancybox" rel="<?=$image["data_type"] ?>" href="images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
<img src="images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border"></a>
<h4 style="color:#2B368D; text-align:center;"><?=$image["title"] ?></h4>
<p style="text-align:center; font-size:15px;"><?=$image["description"] ?></p>
</div>
</li>
<?php
}
?>
</ul><!--END LIST-->
The only thing I can think of off the top of my head would be to create a slider that would contain all the images or use ajax with pagination so there would be no refresh problem.
I have never attempted pagination so please go easy on me here.
Any advice would be appreciated.
Thanks!
look at this example code, which handles the pagination in a simple way.
You can reuse the function getPagesNavi for every list which should be paginated.
It returns the html with the links to navigate through the pages.
If you like to load the pages with ajax you need to do some modifications by yourself. This is only an example to show you how it could work.
$page = intval($_GET['page']);
$myurl = 'index.php?action=list';
$db->select("select * from tablename");
$count_total = $db->getRecords();
$items_per_page = 10;
$start = $page * $items_per_page;
$limit = "limit $start, $items_per_page";
$db->select("select * from tablename $limit");
while($row = $db->fetchArray()) {
// your output here...
}
echo getPageNavi($myurl,$page,$count_total,$items_per_page);
function getPagesNavi($link, $current_page, $count_total, $items_per_page, $number_of_visible_pagelinks_updown = 5, $page_varname = "page") {
$result = "";
if ($count_total <= 0) {
return "";
}
$pages_float = $count_total / $items_per_page;
$number_of_pages = ceil($pages_float) - 1;
$start = $current_page - $number_of_visible_pagelinks_updown;
$end = $current_page + $number_of_visible_pagelinks_updown;
if ($end > $number_of_pages) {
$dif = -$number_of_pages + $end;
$end = $number_of_pages;
$start = $start - $dif;
}
if ($start < 0) {
$dif = -$start;
$end = $end + $dif;
$start = 0;
}
if ($end > $number_of_pages) {
$end = $number_of_pages;
}
$back = $current_page - 1;
$forward = $current_page + 1;
if ($current_page > 0) {
$result .= "
<span class=\"pageItem\"><<</span>
<span class=\"pageItem\"><</span>";
} else {
$result .= "<span class=\"pageItem\"><<</span>";
$result .= "<span class=\"pageItem\"><</span>";
}
for ($i = floor($start); $i <= floor($end); $i++) {
$j = $i + 1;
$class = "";
if ($i == $current_page) {
$class = " currentPageItem";
}
$result.= "<span class=\"pageItem$class\">$j</span>";
}
if ($current_page != $number_of_pages) {
$result .= "<span class=\"pageItem\">></span>";
$result .= "<span class=\"pageItem\">>></span>";
} else {
$result .= "<span class=\"pageItem\">></span>";
$result .= "<span class=\"pageItem\">>></span>";
}
return $result;
}

Is there an easy way to do 4 at a time in a php foreach loop

I have this php foreach loop
<?php $all_news = $this->db->query("Select * from news"); ?>
<div class="inner">
foreach($all_news as $key=>$news){?>
<div class="news <?php echo ($key%2==1)? 'odd': 'even'?>">
<div class="news_img">....<?php echo $news['title'] ?>
But the problem is the $all_news may have 20 results or so but the design only allows me to put for 4 news blocks in each inner div...is there a way make this happen so i have only 4 news divs in each inner div
<?php
$all_news = $this->db->query("Select * from news");
echo '<div class="inner">';
$c = count($all_news);
for($i = 0; $i < $c; $i++){
<div class="news <?php echo ($i%2==1)? 'odd': 'even'?>">
<div class="news_img">....<?php echo $news['title'] ?>
if($i % 4 == 3)
echo '</div><div class="inner">';
}
echo '</div>';
?>
Change your query to only return 4 rows:
SELECT * FROM news LIMIT 4
Alternatively you can change your for-loop.
for($i = 0; $i < min(4, count($all_news)); $i++)
{?>
<div class="news <?php echo ($i%2==1)? 'odd': 'even'?>">
<div class="news_img">....<?php echo $all_news[$i]['title'];
<?}
[edit]
See what you mean now. Create two loops:
<?
$index = 0;
while ($index < count($all_news))
{
$news = $all_news[$index];
?>Start outer div<?
for ($item = 0; $item < 5; $item++)
{
?>Inner div with news item <? echo $news['title'];
}
?>End outer div<?
$index++;
}
You could use two for loops:
<?php $all_news = $this->db->query("Select * from news"); ?>
<?php for($i = 0, $l = count($all_news); $i < $l; $i+=4): ?>
<div class="inner">
<?php for($j = $i; $j < $i+4; $j++): ?>
<div class="news <?php echo ($j%2==1)? 'odd': 'even'?>">
<div class="news_img">....<?php echo $all_news[$j]['title'] ?>
<?php endfor;?>
</div>
<?php endfor;?>
Another option would be array_chunk [docs].
The laziest way would be to just check whether or not you've already done four in the current div on the fly. If you have, close the current div and start a new one:
<div class="inner">
<?php
foreach ($all_news as $key => $news) {
if ($key % 2) {
$oddEven = 'odd';
} else {
$oddEven = 'even';
if ($key && $key % 4 === 0) {
echo '</div><div class="inner">';
}
}
echo "<div class=\"news $oddEven\">";
// ...
}
?>
</div>
Note that this assumes $all_news has an element at 0, so it makes sure that it doesn't close the first, empty div.

Categories