In my last post someone helped me to show my explore posts and it was very helpful. But I wanna show it in a different way.
When I show my news feed or my profile posts and I reach the bottom, it loads more posts. With my previous code, it just loaded all of them and that's a problem because if there a thousand posts they'll all be loaded at once and I don't want that issue. So I wanna set it up in a way that will load more posts as I get to the bottom. It works for my news feed and profile posts but not the explore posts. It immediately gives me the else statement. it's kind of long but I'm guessing the problem is somewhere at the top of method.
public function loadExplorePosts($data, $limit) {
$page = $data['page'];
$userLoggedIn = $this->user_obj->getUsername();
if($page == 1)
$start = 0;
else
$start = ($page - 1) * $limit;
$str = ""; //String to return
$explore_image = $this->con->prepare('SELECT id, body, added_by, date_added, likes, image FROM posts ORDER BY RAND()');
$explore_image->execute();
// $explore_image->store_result();
//$explore_image->bind_result($id, $body, $added_by, $date_added, $likes, $image);
$explore_image_result = $explore_image->get_result();
if ($explore_image_result->num_rows > 0) {
$num_iterations = 0; //Number of results checked (not necasserily posted)
$count = 1;
while ($row = $explore_image_result->fetch_assoc()) {
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$date_time = $row['date_added'];
$imagePath = $row['image'];
if ($userLoggedIn != $added_by) {
//Check if user who posted, has their account closed
$added_by_obj = new User($this->con, $added_by);
if($added_by_obj->isClosed()) {
continue;
}
$user_logged_obj = new User($this->con, $userLoggedIn);
if($user_logged_obj->isFriend($added_by)){
if($num_iterations++ < $start)
continue;
//Once 10 posts have been loaded, break
if($count > $limit) {
break;
}
else {
$count++;
}
if($userLoggedIn == $added_by)
$delete_button = "<button class='delete_button btn-danger' id='post$id'>X</button>";
else
$delete_button = "";
$user_details_query = $this->con->prepare('SELECT first_name, last_name, profile_pic FROM users WHERE username = ?');
$user_details_query->bind_param("s", $added_by);
$user_details_query->execute();
$user_details_query_result = $user_details_query->get_result();
while ($row = $user_details_query_result->fetch_assoc()) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$profile_pic = $row['profile_pic'];
}
?>
<script>
function toggle<?php echo $id; ?>(event){
var target = $(event.target);
if (!target.is('a') && !target.is('button')) {
var element = document.getElementById("toggleComment<?php echo $id; ?>");
if(element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
}
</script>
<?php
$comments_check = $this->con->prepare('SELECT * FROM comments WHERE post_id = ?');
$comments_check->bind_param("i", $id);
$comments_check->execute();
$comments_check->store_result();
$comments_check_num = $comments_check->num_rows;
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_time); //Time of post
$end_date = new DateTime($date_time_now); //Current time
$interval = $start_date->diff($end_date); //Difference between dates
if($interval->y >= 1) {
if($interval->y == 1)
$time_message = $interval->y . " yr"; //1 year ago
else
$time_message = $interval->y . " yrs"; //1+ year ago
}
else if ($interval->m >= 1) {
if($interval->d == 0) {
$days = " ago";
}
else if($interval->d == 1) {
$days = $interval->d . "d";
}
else {
$days = $interval->d . "ds";
}
if($interval->m == 1) {
$time_message = $interval->m . "m ". $days;
}
else {
$time_message = $interval->m . "m ". $days;
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = "Yesterday";
}
else {
$time_message = $interval->d . " days ago";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . "hr";
}
else {
$time_message = $interval->h . "hrs";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . "min";
}
else {
$time_message = $interval->i . " mins";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . "sec";
}
}
if($imagePath != "") {
$imageDiv = "<div class='postedImage'>
<img src='$imagePath'>
</div>";
}
else {
$imageDiv = "";
}
$str .= "<div class='status_post' onClick='javascript:toggle$id(event)'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color:#ACACAC;'>
<a href='$added_by'> $first_name $last_name </a> $user_to $time_message
$delete_button
</div>
<div id='post_body'>
$body
<br>
$imageDiv
<br>
<br>
</div>
<div class='newsfeedPostOptions'>
Comments($comments_check_num)
<iframe src='like.php?post_id=$id' scrolling='no'></iframe>
</div>
</div>
<div class='post_comment' id='toggleComment$id' style='display:none;'>
<iframe src='comment_frame.php?post_id=$id' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr>";
}
?>
<?php
}
} //End while loop
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
<input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;' class='noMorePostsText'><center> No more posts to show! </center></p><br><br>";
}
echo $str;
}
EDIT -----------
I just tried this and the if echo showed up so maybe it's the way I'm trying to output the results:
if ($explore_image_result > 0) {
echo "Found";
} else {
echo "not";
}
Related
I am trying to show a color if my ternary operator comes back as true and another one if it comes back as false. The operator is working but one thing is off. The code inside of the double quotes shows instead of the actual color itself. Anyone know how to fix this ?
$msg .= ($row['opened'] == '0') ? "background-color: #DDEDFF;" : "background-color: #000000;";
EDIT!!! - These are the only times my $msg variable shows up
public function getLatestMessage ($userLoggedIn, $user2) {
$query = $this->con->prepare('SELECT body, user_to, opened, date FROM messages WHERE
user_to = ? AND user_from = ? OR user_to = ? AND user_from = ? ORDER BY id DESC LIMIT 1');
$query->bind_param("ssss", $userLoggedIn, $user2, $user2, $userLoggedIn);
$query->execute();
$query_result = $query->get_result();
$msg = ""; //to hold the message data
if ($row = $query_result->fetch_assoc()) { //don't need a while here because we've limited the query to one record
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($row['date']); //Time of post
$end_date = new DateTime($date_time_now); //Current time
$interval = $start_date->diff($end_date); //Difference between dates
if($interval->y >= 1) {
if($interval->y == 1)
$time_message = $interval->y . "yr"; //1 year ago
else
$time_message = $interval->y . "yrs"; //1+ year ago
}
else if ($interval-> m >= 1) {
if($interval->d == 0) {
$days = " ago";
}
else if($interval->d == 1) {
$days = $interval->d . "d";
}
else {
$days = $interval->d . "d";
}
if($interval->m == 1) {
$time_message = $interval->m . "month";
}
else {
$time_message = $interval->m . "months";
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = "Yesterday";
}
else {
$time_message = $interval->d . "d ";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . "hr";
}
else {
$time_message = $interval->h . "hrs";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . "m";
}
else {
$time_message = $interval->i . "m";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . " seconds ago";
}
}
$msg .= ($row['user_to'] == $userLoggedIn) ? "They said: " : "You said: ";
$msg .= ' ';
$msg .= $body = $row['body'];
$msg .= ' ';
$msg .= $time_message ;
$msg .= ' ';
$msg .= ($row['opened'] == '0') ? "background-color: #DDEDFF;" : "background-color: #000000;";
}
return $msg;
}
Your code is doing exactly what you are telling it: outputting a string that says "background-color: ... ".
How would the browser know you want to style the text with that color instead of presenting those words to the user?
You need to instead specify for the browser that this is a style you are giving it.
Instead of
$msg .= ($row['opened'] == '0') ? "background-color: #DDEDFF;" : "background-color: #000000;";
try something like:
$color = $row['opened'] == '0' ? "#DDEDFF" : "#000000";
$msg .= "<span style='background-color:$color'>THE TEXT YOU WANT TO COLORIZE</span>";
COMPLETE EXAMPLE
<?php
function getLatestMessage($opened) {
$color = $opened ? "#DDEDFF" : "#000000";
$msg = "<span style='background-color:$color'>THE TEXT YOU WANT TO COLORIZE</span>";
return $msg;
}
echo getLatestMessage(true);
echo getLatestMessage(false);
?>
Edit: Issue has been resolved. The culprit was a misplaced single quote :P
The first image where content is getting displayed:
The second image is where no content is getting displayed
I have asked this question already a few days ago and my problem got solved there, but suddenly the problem occurred again and I can't seem to find the solution for it. What i'm trying to do is load the posts that will exceed 10 posts while scrolling but no posts are getting displayed when I'm adding Ajax.
Here is the code:
index.php code:
<?php
include("includes/header.php");
include("includes/classes/User.php");
include("includes/classes/Post.php");
if(isset($_POST['post']))
{
$post=new Post($con,$userLoggedIn);
$post->submitPost($_POST['post_text'],'none');
}
?>
<div class="user_details column">
<div class="user_details_left_right">
<a href="<?php echo $userLoggedIn; ?>">
<?php
echo $user['first_name'] . " " . $user['last_name'];
?>
</a>
<br>
<?php
echo "My Posts: " . $user['num_post'] . "<br>";
echo "Likes: " . $user['num_likes'];
?>
</div>
</div>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Write something here..."></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<!--<?php
$post=new Post($con,$userLoggedIn);
$post->loadPostsFriends();
?>-->
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function()
{
$('#loading').show();
//ajax request for loading 1st posts
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data)
{
$("#loading").hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function()
{
var height=$('.posts_area').height(); //div containing posts
var scroll_top=$(this).scrollTop();
var page=$('.posts_area').find('.nextPage').val();
var noMorePosts=$('posts_area').find('.noMorePosts').val();
if((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false')
{
$('#loading').show();
alert("hello");
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response)
{
$('.posts_area').find('.nextPage').remove(); //removes current next page
$('.posts_area').find('.noMorePosts').remove();
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //If end
return false;
}); //ending of $(window).scroll(function()
});
</script>
</div>
</body>
</html>
Post.php code:
<?php
class Post
{
private $user_obj;
private $con;
public function __construct($con,$user)
{
$this->con = $con;
$this->user_obj = new User($con,$user);
}
//$user_obj=new User($con,$userLoggedIn)
public function submitPost($body,$user_to)
{
$body=strip_tags($body); //To remove any HTML tag
$body=mysqli_escape_string($this->con, $body);
$check_empty=preg_replace('/\s+/','',$body); //To delete spaces
if($check_empty != "")
{
//Date and time
$date_added=date("Y-m-d H:i:s");
//get user name
$added_by=$this->user_obj->getUsername();
//If user is watching his/her own profile, user_to is none
if($user_to == $added_by)
{
$user_to = "none";
}
//Insert post
$query = mysqli_query($this->con,"INSERT INTO posts VALUES('','$body','$added_by','$user_to','$date_added','no','no','0')");
$returned_id=mysqli_insert_id($this->con);
//Insert noti
//Update posts count
$num_posts=$this->user_obj->getNumPosts();
$num_posts++;
$update_query=mysqli_query($this->con,"UPDATE users SET num_post='$num_posts' WHERE username='$added_by'");
}
}
public function loadPostsFriends($data,$limit)
{
$page=$data['page'];
$userLoggedIn=$this->user_obj->getUsername();
if($page == 1)
$start = 0;
else
$start = ($page-1) * $limit;
$str=""; //Str to return
$data_query=mysqli_query($this->con,"SELECT * FROM posts WHERE deleted='no' ORDER BY id DESC");
if(mysqli_num_rows($data_query) > 0)
{
$num_iterations = 0; //number of result checking
$count=1;
while($row=mysqli_fetch_array($data_query))
{
$id=$row['id'];
$body=$row['body'];
$data[] = $id;
$data[] = $body;
$added_by=$row['added_by'];
$date_time=$row['date_added'];
//prepare user_to string to include it even if not posted to an user
if($row['user_to'] == "none")
{
$user_to="";
}
else
{
$user_to_obj=new User($con,$row['user_to']);
$user_to_name=$user_to_obj->getFirstAndLastName();
$user_to="wrote to <a href'" . $row['user_to'] . "'>" . $user_to_name . "</a>";
}
//check if userwho posted has their account closed
$added_by_obj=new User($this->con,$added_by);
if($added_by_obj->isClosed())
{
continue;
}
if($num_iterations++ < $start)
continue;
//once 10 posts loaded just break
if($count > $limit)
{
break;
}
else
{
$count++;
}
$user_details_query=mysqli_query($this->con,"SELECT first_name,last_name,profile_pic FROM users WHERE username='$added_by'");
$user_row=mysqli_fetch_array($user_details_query);
$first_name=$user_row['first_name'];
$last_name=$user_row['last_name'];
$profile_pic=$user_row['profile_pic'];
//Datetime
$date_time_now=date("Y-m-d H:i:s");
$start_date=new DateTime($date_time); //Post date & time
$end_date=new DateTime($date_time_now); //Current time
$interval=$start_date->diff($end_date); //Difference between above 2 dates
if($interval->y >= 1)
{
if($interval==1)
$time_message=$interval->y . "year ago"; //1 year ago
else
$time_message=$interval->y . "year ago"; //More than 1 year ago
}
else if($interval-> m >= 1)
{
if($interval->d == 0)
{
$days=" ago";
}
else if($interval-> d == 1)
{
$days=$interval->d . " day ago";
}
else
{
$days=$interval->d . " days ago";
}
if($interval->m == 1)
{
$time_message=$interval->m . " month" . $days;
}
else
{
$time_message=$interval->m . " months" . $days;
}
}
else if($interval->d >= 1)
{
if($interval-> d == 1)
{
$time_message="Yesterday";
}
else
{
$time_message=$interval->d . " days ago";
}
}
else if($interval->h >=1)
{
if($interval-> h == 1)
{
$time_message=$interval->h . " hour ago";
}
else
{
$time_message=$interval->h . " hours ago";
}
}
else if($interval->i >=1)
{
if($interval-> i == 1)
{
$time_message=$interval->i . " minute ago";
}
else
{
$time_message=$interval->i . " minutes ago";
}
}
else
{
if($interval-> s < 30)
{
$time_message="Just Now!";
}
else
{
$time_message=$interval->s . " seconds ago";
}
}
$str .= "<div class='status_post'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color:#BDBDBD;'>
<a href='$added_by'> $first_name $last_name </a> $user_to $time_message
</div>
<div id='post_body'>$body<br></div>
</div><hr>";
}
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page+1) . "'><input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align:center;'>No more posts!</p>";
}
echo $str;
}
}
?>
user.php code:
<?php
class User
{
private $user;
private $con;
public function __construct($con,$user)
{
$this->con = $con;
$user_details_query=mysqli_query($con,"SELECT * FROM users WHERE username='$user'");
$this->user = mysqli_fetch_array($user_details_query);
}
//$user_obj=new User($con,$userLoggedIn)
public function getUsername()
{
return $this->user['username'];
}
public function getNumPosts()
{
$username=$this->user['username'];
$query=mysqli_query($this->con,"SELECT num_post FROM users WHERE username='$username'");
$row=mysqli_fetch_array($query);
return $row['num_post'];
}
public function getFirstAndLastName()
{
$username=$this->user['username'];
$query=mysqli_query($this->con, "SELECT first_name, last_name FROM users WHERE username='$username'");
$row=mysqli_fetch_array($query);
return $row['first_name'] . " " . $row['last_name'];
}
public function isClosed()
{
$username=$this->user['username'];
$query=mysqli_query($this->con,"SELECT user_closed FROM users WHERE username='$username'");
$row=mysqli_fetch_array($query);
if($row['user_closed']=='yes')
return true;
else
return false;
}
public function isFriend($username_to_check)
{
$usernameComma="," . $username_to_check . ",";
if((strstr($this->user['friend_array'],$usernameComma)) || $username_to_check==$this->user['username'])
{
return true;
}
else
{
return false;
}
}
}
?>
ajaxloadpost.php code:
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit=10; //Limit post to 10 each time
$posts=new Post($con,$_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST,$limit);
?>
I would like to add a count == 0 which if it is the case, just outputs 'please contact us to find out the dates', but I can't seem to get it to work. Please can someone advise?
$count = 0;
$your_repeater = get_field('add_date');
if ($your_repeater) {
while (have_rows('add_date')):
the_row();
$count++;
$my_field = get_sub_field('course_date');
if ($count == 0) {
echo 'please contact us to find out dates';
} else {
echo '';
}
if ($count == 1) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
// echo $my_field .', ';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>1. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo 'Contact us to find out more';
} else {
echo '';
}
}
if ($count == 2) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>2. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo '<img src="' .bloginfo('url').'/wp-content/themes/derbyskillbuild site/images/hourglass.png" />';
} else {
echo '';
}
}
if ($count == 3) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b> 3. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
} else {
echo '';
}
}
if ($count == 4) {
}
if ($count == 5) {
}
echo '</ul>';
endwhile;
}
It appears that you are checking the count way too soon in your code.
You start with a $count = 0;, but then in the while loop you first do $count++. So, at this point, the count is 1. Then a few lines later you check this:
if ($count == 0) {
echo 'please contact us to find out dates';
}
This will never return true, since you just did a $count++ from 0, so at this point it's always at least 1. It seems that this check should be outside of your while loop and you're currently closing the loop way too late.
I am working on WPF where I have two datepickers when I try to retrieve the information on date range it displays only one record on all dates(same record displaying multiple times eg : date chosen from 01/10/2013 - 3/10/2013) where I have 3 different records on each day but my output is the first record displayed 3 times with same date and time.
function cpWhitelistStats() {
$startDate = $_POST['startDate'];
$startDateTime = "$startDate 00:00:00";
$endDate = $_POST['endDate'];
$endDateTime = "$endDate 23:59:59";
$cpId = $_POST['id'];
$cpName = etCommonCpNameById($cpId);
print "<h2 style=\"text-align: center;\">Permitted Vehicle Summary</h2>";
print "<h2 style=\"text-align: center;\">for $cpName</h2>";
$tmpDate = explode("/", $startDate);
$startYear = $tmpDate[2];
$startMonth= $tmpDate[1];
$startDay = $tmpDate[0];
$tmpDate = explode("/", $endDate);
$endYear = $tmpDate[2];
$endMonth= $tmpDate[1];
$endDay = $tmpDate[0];
$startDateTime = "$startYear-$startMonth-$startDay 00:00:00";
$endDateTime = "$endYear-$endMonth-$endDay 23:59:59";
$custId = $_SESSION['customerID'];
$realCustomerId = $_SESSION['realCustomerId'];
$maxVal = 0;
if ($custId != "") {
$conn = &newEtConn($custId);
// Get the whitelist plates
$staticWhitelistArray = etCommonMkWhitelist($conn, $cpId);
array_shift($staticWhitelistArray);
$startLoopDate = strtotime($startDateTime);
$endLoopDate = strtotime($endDateTime);
$oneDay = 60 * 60 * 24;
// Get the entries
$plateList = array_keys($staticWhitelistArray);
$plate_lookup = implode('","', $plateList);
$sql = "SELECT plate, entry_datetime, exit_datetime FROM stats WHERE plate IN (\"$plate_lookup\") AND entry_datetime > \"$startDateTime\" AND entry_datetime < \"$endDateTime\" AND carpark_id=\"$cpId\" ";
$result = $conn->Execute($sql);
if (!$result) {
print $conn->ErrorMsg();
exit;
}
$rows = $result->fields;
if ($rows != "") {
unset($myArray);
foreach($result as $values) {
$plate = $values['plate'];
$new_platelist[] = $plate;
$inDateTime = $values['entry_datetime'];
$outDateTime = $values['exit_datetime'];
$tmp = explode(' ', $inDateTime);
$inDate = $tmp[0];
$in_ts = strtotime($inDateTime);
$out_ts = strtotime($outDateTime);
$duration = $out_ts - $in_ts;
$dur_array = intToDateArray($duration);
$dur_string = '';
if ($dur_array['days'] > 0) {
$dur_string .= $dur_array['days'] . ' days ';
}
if ($dur_array['hours'] > 0) {
$dur_string .= $dur_array['hours'] . ' hours ';
}
if ($dur_array['mins'] > 0) {
$dur_string .= $dur_array['mins'] . ' minutes ';
}
if ($dur_array['secs'] > 0) {
$dur_string .= $dur_array['secs'] . ' secs ';
}
$myArray[$plate][] = array($inDateTime, $outDateTime, $inDate, $dur_string);
}
}
while ($startLoopDate < $endLoopDate) {
$dayString = strftime("%a, %d %B %Y", $startLoopDate);
$dayCheck = strftime("%Y-%m-%d", $startLoopDate);
print "<h2>$dayString</h2>";
print "<table width=\"100%\">";
print " <tr>";
print " <th>VRM</th>";
print " <th>Permit Group</th>";
print " <th>Entry Time</th>";
print " <th>Exit Time</th>";
print " <th>Duration</th>";
print " </tr>";
foreach($new_platelist as $wlPlate) {
if ($myArray[$wlPlate][0][2] == $dayCheck) {
print "<tr>";
print "<td>$wlPlate</td>";
if (isset($myArray[$wlPlate])) {
print "<td>".$staticWhitelistArray[$wlPlate]['groupname']."</td>";
print "<td>".$myArray[$wlPlate][0][0]."</td>";
print "<td>".$myArray[$wlPlate][0][1]."</td>";
print "<td>".$myArray[$wlPlate][0][3]."</td>";
}
else {
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
print "<td>Vehicle Not Seen</td>";
}
print "</tr>";
}
}
print "</table>";
$startLoopDate = $startLoopDate + $oneDay;
}
}
}
Can you echo this query so we can see what's actually being sent...
$sql = "
SELECT plate
, entry_datetime
, exit_datetime
FROM stats
WHERE plate IN ('$plate_lookup')
AND entry_datetime BETWEEN '$startDateTime' AND '$endDateTime'
AND carpark_id= '$cpId';
";
(This isn't an answer, but I wanted to make use of the additional formatting options)
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
echo "";
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
Pagination is working correctly for select $today. Here pagination is not taking value to second page in the case of select $mydate. If second page of $mydate clicks, again going to $today. ie Second click is not posting $mydate to next page. How can I take the value to second page?
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
function pagination in your code is not returning the resulting mysql query resource, and your code is not receiving that from the pagination function call
you need
to add return $pg_result; in your pagination function
and add $result=pagination(....
Edit:
Sorry, I noticed you added pg_result to global, which does not need return and the solution I said, but you don't need mysql_query and fetch before that and I don't see where you print the results. there is only echo "", you can try the one I edited last, and see if it works for you.
Edit:
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
//$result=mysql_query($sql);
$pg_result=pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '' && is_resource($pg_result))
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
var_dump($data);
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
return $pg_result;
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
Looks like you're mixing up the concept of $_POST and $_GET.
By having your pagination links point to '<a href="'.$pg_page_name.'?page_id='.$i . $pg_user_param.'"... You should be intercepting $_GET['page_id'] before you make your SQL query.
Your top code references $_POST['datepicker'] but you don't mention a form anywhere and your pagination links certainly aren't posting that data in your example.
You should use $pg_param = ""; to pass your own query parameters. Ex: &date=$date_value:
$pg_param = "&date=$date_value";