Displaying same time passed in while through time_passed function - php

I'm doing a while() and in it I use a function to display a prettier "time since posted", but for some reason, all of the results end up in the same "time passed" (the last result) when echoing it out
only the time will become the same, not the other content. Here's my code, trimmed down a bit:
<?php
$result = $db->query("SELECT * FROM $dbboardname WHERE replyto = '' AND hidden = '' ORDER BY bump ASC LIMIT $pagenum, 20") OR die($db->error);
while($rowaaa = $result->fetch_assoc()){
$id = $rowaaa['id'];
$textcontent = $rowaaa['textcontent'];
$imageurl = $rowaaa['imageurl'];
$name = $rowaaa['nameyes'];
$timestamps = $rowaaa['timestamp'];
$timestamps = time_passed($timestamps);
$tripcode = $rowaaa['tripcode'];
?>
<div class="post-index" data-postid="<?php echo($id); ?>" name="<?php echo($id); ?>" id="<?php echo($id); ?>">
<div class="image-container-index">
<?php if(!empty($imageurl)){ ?>
<img src="<?php echo($imageurl); ?>" alt="image <?php echo($id); ?>" />
<?php }else{
?>
<img src="/images/noimage.png" alt="no image" />
<?php
}
?>
</div>
<div class="post-info">
<span class="post-info-left">
#<?php echo($id); ?> by <?php if (!empty($name)){
echo(substr($name, 0, 8));
}else{
echo("norseman");
}
?>
</span>
<span class="post-info-right">
<?php echo($timestamps); ?>
</span>
<div class="clear"></div>
</div>
<div class="post-preview">
<?php echo(substr($textcontent, 0, 150)); ?>
</div>
</div>
<?php
}
?>
<div class="clear"></div>
And here is the time_passed() function:
function time_passed($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
So my guess is that for every new "while", it edits all of the timestamps. I just don't know how to fix this, considering the string is inside an while() statement.
EDIT:
I noticed my timestamp updated because I altered the bump row on every post each time a new thread was posted, this way all the timestamps were updated. I fixed the timestamp row now.

It looks like your time_passed routine is expecting a datetime - not a timestamp, perhaps that is the error.
function time_passed($datetime, $full = false) {
Try to change this line:
$ago = new DateTime($datetime);
to this:
$ago = new DateTime(date('r',$datetime));
I hope that helps.

Let's try this again ... since they are all coming out the same, it sounds like the value you are passing to the function is wrong then - try putting a a test around the timestamp assignment:
$timestamps = $rowaaa['timestamp'];
echo "Made |$timestamps| from |{$rowaaa['timestamp']}<br/>\n";
$timestamps = time_passed($timestamps);
echo "Now timestamps is |$timestamps| from time_passed() function<br/>\n";
If they are all the same, the problem is in your data.
You can also show the entire content of the array by doing this:
echo "Full Details<pre>\n".print_r($rowaaa,1)."\n</pre>\n";

Related

How to add class in a string in PHP

I would like to put class inside this string :
<div class="date-custom-page">
<?php
$date = get_field('jour_de_levenement', false, false);
$time = strtotime($date);
?>
<?php $dateformatstring = "<p class='date-event'>j</p><p class='month'>F Y</p>"; ?>
<?php $unixtimestamp = strtotime(get_field('jour_de_levenement', false, false));
echo date_i18n($dateformatstring, $unixtimestamp); ?>
I have tried this but only the p is taken, not the class.
Can someone help me ?
Thanks a lot !
Just use this :
$dateformatstring = "<p class='date-event'>j</p><p class='month'>F Y</p>";

Zabuto Calendar with ajax

How can I get the events stored in my db to show in the calendar ?
I can't seem to figure out how to replace the random dates with my own ones :/
Basically I have to loop through the data i get from my db don't I ?
And put the data in the JSON format ...
Can I use a foreach loop ?
this is the code provided by the zabuto calendar download site
<?php include_once 'includes/sessions.php'; ?>
<?php include_once 'includes/connect.php';
/**
* Example of JSON data for calendar
*
* #package zabuto_calendar
*/
if (!empty($_REQUEST['year']) && !empty($_REQUEST['month'])) {
$year = intval($_REQUEST['year']);
$month = intval($_REQUEST['month']);
$lastday = intval(strftime('%d', mktime(0, 0, 0, ($month == 12 ? 1 : $month + 1), 0, ($month == 12 ? $year + 1 : $year))));
$dates = array();
for ($i = 0; $i <= (rand(4, 10)); $i++) {
$date = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-' . str_pad(rand(1, $lastday), 2, '0', STR_PAD_LEFT);
$dates[$i] = array(
'date' => $date,
'badge' => ($i & 1) ? true : false,
'title' => 'Example for ' . $date,
'body' => '<p class="lead">Information for this date</p><p>You can add <strong>html</strong> in this block</p>',
'footer' => 'Extra information',
);
if (!empty($_REQUEST['grade'])) {
$dates[$i]['badge'] = false;
$dates[$i]['classname'] = 'grade-' . rand(1, 4);
}
if (!empty($_REQUEST['action'])) {
$dates[$i]['title'] = 'Action for ' . $date;
$dates[$i]['body'] = '<p>The footer of this modal window consists of two buttons. One button to close the modal window without further action.</p>';
$dates[$i]['body'] .= '<p>The other button [Go ahead!] fires myFunction(). The content for the footer was obtained with the AJAX request.</p>';
$dates[$i]['body'] .= '<p>The ID needed for the function can be retrieved with jQuery: <code>dateId = $(this).closest(\'.modal\').attr(\'dateId\');</code></p>';
$dates[$i]['body'] .= '<p>The second argument is true in this case, so the function can handle closing the modal window: <code>myFunction(dateId, true);</code></p>';
$dates[$i]['footer'] = '
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="dateId = $(this).closest(\'.modal\').attr(\'dateId\'); myDateFunction(dateId, true);">Go ahead!</button>
';
}
}
echo json_encode($dates);
} else {
echo json_encode(array());
}

Create a loop using associative arrays

I want to put this in a loop because it needs to be repeated 6 times, is it true that using variable variables is a bad practice? Do I need associative arrays?
Basically the 'c1' inside the variable needs to progressively change into 'c2', 'c3'...etc
<?php if ($pm_c1_djwd !== '') { ?>
<div>
<span style="width:<?php echo $pm_width_c1;?>%"></span>
<span><?php echo $pm_description_c1; ?></span>
</div>
<?php } ?>
Many Thanks
Why not try regular arrays?
<?php
// Warning: Typed raw in the textarea
$pm_width = array(100, 100, 100, 100, 100, 100);
$pm_description = array(
"Gizmo",
"Doodad",
"Widget",
"Dohicky",
"Thing-me-a-bob",
"Marvelous toy my father gave to me."
);
$pm_c1_djwd = "Snod";
if ($pm_c1_djwd !== '') {
for ($i = 0; $i < count($pm_description); $i++) {
$width = $pm_width[$i];
$desc = $pm_description[$i];
echo "<div>";
echo "<span style='width:${width}%'>$desc</span>";
echo '</div>';
echo PHP_EOL;
}
}
?>
Instead of having a variable for each field like $pm_description_c1, ..c2 and so on, put them in an associative array:
$pms = array(
array('description' => 'your description', 'width' => '123px', 'djwd' = 'what'),
array('description' => 'Second item', 'width' => '123px', 'djwd' = '')
);
Then loop through them:
<?php
foreach ($pms as $pm) {
if ($pm['djwd' !== '') {
?>
<div>
<span style="width:<?php echo $pm['width'];?>%"></span>
<span><?php echo $pm['description']; ?></span>
</div>
<?php
}
}
?>
You can use variable variables for the thing you are asking...
<?php
$i = 0;
while( $i < 6 ){
$i ++;
$variable = "pm_c".$i."_djwd";
$variable2 = "pm_description_c".$i."";
if (isset($$variable) && $$variable != '') { ?>
<div>
<span style="width:<?php echo $$variable;?>%"></span>
<span><?php echo $$variable2; ?></span>
</div>
<?php }
}

Ajax Paging with php and mysql

I am trying to setup paging on my site using Ajax, I've inherited a script and put it into practice at the following link - http://www.testing.arrivaldesign.co.uk/properties.
I've got it working to an extent, but it's set to show the first 9 records and then carry on from there, but it's only showing the first 9 on the first page, but then when you click to the next page it just repeats 4 of the existing records.
As far as I can see it's to do with limit on my query, but I don't know how to get it working?
This is the code for the ajax side of things.
<?php
include('Connections/connection.php');
include 'functions.php';
// Pagination params
$basePath = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
$qString = $_REQUEST['qString'];
$items = $_REQUEST['items'];
$loadPage = $_REQUEST['p'];
$current = $_REQUEST['current'];
$limit = $loadPage*$items;
$min = ($max-$items)+1;
mysql_select_db($database, $conn);
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, $limit";
$RSproperty = mysql_query($query_RSproperty, $conn) or die(mysql_error());
$row_RSproperty = mysql_fetch_assoc($RSproperty);
$totalRows_RSproperty = mysql_num_rows($RSproperty);
$maxItems = $totalRows_RSproperty;
// New pagination
$pagination = paginator($basePath . $qString, $loadPage, $maxItems, $items);
// Direction is important for the script to determine which way to animate, left or right.
$direction = 'left';
if ($current < $loadPage) {
$direction = 'right';
}
$paginatedStyle = 'style="left:'.($direction == 'left' ? '0' : '-960px').';"';
// The paginated content HTML slide
$page = '<div class="paginated" id="" '.$paginatedStyle.'>';
ob_start();
do {
?>
<div class="grid-1third res-block">
<div class="prop-brief-desc">
<div class="grid-140"><img src="/prop-images/thumbs/<?php echo $row_RSproperty['propImage1']; ?>" width="140" height="105" alt=""></div>
<div class="grid-140 fr">
<h2><?php echo $row_RSproperty['propBeds']; ?> Bed <?php echo $row_RSproperty['typeName']; ?></h2>
<?php
$fulladdress = $row_RSproperty['propAddress1'] . '<br />' . $row_RSproperty['propCity'] . ', ' . $row_RSproperty['propCounty'] . '<br />' . $row_RSproperty['propPostcode'];
?>
<p><?php echo $fulladdress; ?></p>
</div>
</div>
<div class="prop-brief-options<?php echo $no == 2 || $no == 3 ? " hide" : ""; ?>" id="newopt<?php echo $no; ?>">
<div class="grid-140"> Details Arrange Viewing Place Bid Buy it Now </div>
<div class="grid-140 fr">
<dl>
<dt>Auction Ending:</dt>
<dd><?php
if(!function_exists('countdown')) {
function countdown($year, $month, $day, $hour, $minute) {
$the_countdown_date = mktime($hour, $minute, 0, $month, $day, $year, -1);
$current = time();
$difference = $the_countdown_date - $current;
if ($difference < 0) $difference = 0;
$days = floor($difference/60/60/24);
$hours = floor(($difference - $days*60*60*24)/60/60);
$minutes = floor(($difference - $days*60*60*24 - $hours*60*60)/60);
echo $days."d ".$hours."h ".$minutes."m";
}
}
$theyear = date("Y",strtotime($row_RSproperty['propEndDate']));
$themonth = date("n",strtotime($row_RSproperty['propEndDate']));
$theday = date("d",strtotime($row_RSproperty['propEndDate']));
$thehour = date("H",strtotime($row_RSproperty['propEndDate']));
$theminute = date("i",strtotime($row_RSproperty['propEndDate']));
countdown($theyear,$themonth,$theday,$thehour,$theminute);
?></dd>
<?php if ($row_RSproperty['propCurrBid'] > 0) { ?>
<dt>Current bid:</dt>
<dd>£<?php echo number_format($row_RSproperty['propCurrBid']); ?></dd>
<?php } else { ?>
<dt>Starting Price:</dt>
<dd>£<?php echo number_format($row_RSproperty['propStartPrice']); ?></dd>
<?php } ?>
<dt>Buy it now:</dt>
<dd><span class="green">£<?php echo number_format($row_RSproperty['propBinPrice']); ?></span></dd>
</dl>
</div>
</div>
</div>
<?php
} while ($row_RSproperty = mysql_fetch_array($RSproperty));
/*while ($min <= $max) {
$page .= '<li>'.$min.'</li>';
$min++;
}*/
$page .= ob_get_contents();
ob_end_clean();
$page .= '</div>';
// return the JSON
echo json_encode(array( 'pagination' => $pagination, 'page' => $page, 'current' => $loadPage ));
exit;
?>
Many thanks
Chris
That's because you have hard coded LIMIT as 0 in your query
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, $limit";
So when you move on second page, the query must be getting generated like follow
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT 0, 4";
hence you re getting first 4 records. If you want to retrieve the next set of records on subsequent pages, then you have to make 0 in LIMIT 0, $limit dynamic like:
$query_RSproperty = "SELECT properties.*, type.* FROM (properties LEFT JOIN type ON properties.propType=type.typeID) WHERE offline = 'N' ORDER BY propID ASC LIMIT $offset, $limit";
You have to calculate $offset depending on how much results you are displaying per page. On first page, offset will always be 0. If you are displaying 10 records per page, then on second page, offset will be 11, on third offset will be 21 and so on.

PHP: Nested Foreach loop problems

I am attempting to display a list of users based on a month value. I want to display January then all the users associated with it etc...
What i have now is working correctly for the first months then does nothing after. I have comments in the code and a live version of this code is running at: http://blog.funeraldirectorslife.com/participants/
<?php
/*
Template Name: Participants
*/
?>
<?php
function display_user($author, $month){
$ID = $author->ID;
$full_name = get_the_author_meta('display_name', $ID);
$usr_name = get_the_author_meta('user_nicename', $ID);
$sab_descriptiom = get_cimyFieldValue("$ID", 'Sabbatical_desc');
$sab_start = get_cimyFieldValue("$ID", 'Sabbatical_Start');
$sab_end = get_cimyFieldValue("$ID", 'Sabbatical_End');
$sab_month = get_cimyFieldValue("$ID", 'Sabbatical_Month');
$author_posts = $author->num_posts;
//$months = array(January, February, March, April, May, June, July, August, September, October, November, December);
//echo $sab_month;
if ($sab_month == $month){
echo "<li>";
echo "<h4 class=\"nomar\"><a href=\"http://blog.funeraldirectorslife.com/author/"
. $usr_name
."\">"
.$full_name
."("
. $author_posts
. ")"
. "</a>"
. "</h4>";
echo $sab_start
. " - "
. $sab_end
. "<br />";
echo $sab_descriptiom
. "<br />"
. $sab_month . "</br>" . "</li>" . "\n";
}
else {
return;
}
}
?>
<?php get_header(); ?>
<div id="bd" class="grid_12 alpha omega clearfix">
<?php get_sidebar(); ?>
<div id="main" class="grid_9 omega">
<?php include(TEMPLATEPATH . '/banner.php'); ?>
<div class="unit">
<!--
<div class="head">
<div class="title"><h3><span>Blog Entries</span></h3></div>
</div>
//-->
<div class="body clearfix">
<ul class="styled_list">
<li class ="alpha"><h3 class="nomar"><span><?php the_title(); ?></span></h3></li>
<?php
//grab authors ids, post count, and extended info from database
//fill $authors array with data
$sql = "SELECT * FROM `wp_users` WHERE 1 ORDER BY ID";
$results = $wpdb->get_results($sql);
$authors = $results;
$author_count = array();
$rows = $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author");
foreach ($rows as $row) {
$author_count[$row->post_author] = $row->count;
}
//combine queries
foreach( $authors as $author ) {
$author->num_posts = (isset($author_count[$author->ID])) ? $author_count[$author->ID] : 0;
}
//month array for comparing with sabbatical month
$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December');
//tried old method for iterating arrays --> same result
/*reset($months);
while (list($key, $month) = each($months)){
echo "<h2 class=\"nomar\">" . $month . "</h2>" . "\n";
foreach($authors as $author) {
display_user($author, $month);
//echo $author->ID;
}
}*/
foreach($months as $month ) {
echo "<h2 class=\"nomar\">" . $month . "</h2>" . "\n";
foreach($authors as $author) {
display_user($author, $month);
//echo $author->ID;
}
//lists authors by ID - just making sure array is intact after each author loop
/*foreach($authors as $author) {
$ID = $author->ID;
$foo = get_cimyFieldValue("$ID", 'Sabbatical_Month');
echo $ID . $foo . "<br /> . "\n"";
}*/
}
?>
</ul>
</div>
</div>
</div>
</div>
<?php get_footer();
?>
I'm not sure if it will work properly, but I have updated your code somewhat. Mainly I added the trim() function when comparing your $sab_month and $month but I also cleaned up your code a bit. You can embed variables inside of a double-quoted string in PHP, so you don't have to concatenate them :-)
<?php /* Template Name: Participants */ ?>
<?php
function display_user($author, $month){
$ID = $author->ID;
$full_name = get_the_author_meta('display_name', $ID);
$usr_name = get_the_author_meta('user_nicename', $ID);
$sab_descriptiom = get_cimyFieldValue("$ID", 'Sabbatical_desc');
$sab_start = get_cimyFieldValue("$ID", 'Sabbatical_Start');
$sab_end = get_cimyFieldValue("$ID", 'Sabbatical_End');
$sab_month = get_cimyFieldValue("$ID", 'Sabbatical_Month');
$author_posts = $author->num_posts;
//$months = array(January, February, March, April, May, June, July, August, September, October, November, December);
//echo $sab_month;
if (trim($sab_month) == trim($month)){
echo "<li>";
echo " <h4 class='nomar'><a href='http://blog.funeraldirectorslife.com/author/$usr_name'>$full_name($author_posts)</a></h4>";
echo " $sab_start - $sab_end<br />";
echo " $sab_descriptiom<br />";
echo " $sab_month</br>";
echo "</li>\n";
}
/* Not necessary. The function will return when it hits the end
else {
return;
}
*/
}
?>
<?php get_header(); ?>
<div id="bd" class="grid_12 alpha omega clearfix">
<?php get_sidebar(); ?>
<div id="main" class="grid_9 omega">
<?php include(TEMPLATEPATH . '/banner.php'); ?>
<div class="unit">
<!--
<div class="head">
<div class="title"><h3><span>Blog Entries</span></h3></div>
</div>
//-->
<div class="body clearfix">
<ul class="styled_list">
<li class ="alpha"><h3 class="nomar"><span><?php the_title(); ?></span></h3></li>
<?php
//grab authors ids, post count, and extended info from database
//fill $authors array with data
$sql = "SELECT * FROM `wp_users` WHERE 1 ORDER BY ID";
$results = $wpdb->get_results($sql);
$authors = $results;
$author_count = array();
$rows = $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author");
foreach ($rows as $row) {
$author_count[$row->post_author] = $row->count;
}
//combine queries
foreach( $authors as $author ) {
$author->num_posts = (isset($author_count[$author->ID])) ? $author_count[$author->ID] : 0;
}
//month array for comparing with sabbatical month
$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December');
//tried old method for iterating arrays --> same result
/*reset($months);
while (list($key, $month) = each($months)){
echo "<h2 class=\"nomar\">" . $month . "</h2>" . "\n";
foreach($authors as $author) {
display_user($author, $month);
//echo $author->ID;
}
}*/
foreach($months as $month) {
echo "<h2 class='nomar'>$month</h2>\n";
foreach($authors as $author) {
display_user($author, $month);
//echo $author->ID;
}
//lists authors by ID - just making sure array is intact after each author loop
/*foreach($authors as $author) {
$ID = $author->ID;
$foo = get_cimyFieldValue("$ID", 'Sabbatical_Month');
echo $ID . $foo . "<br /> . "\n"";
}*/
}
?>
</ul>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
appearantly this if fails after the first month if ($sab_month == $month)
Maybe some typo, case differences perhaps? I'd try adding echo "Sab month == ",$sab_month,"\n script month ==",$month;
Put it just before the if. good luck
I know I used comma's , thats just another way of using echo.

Categories