i have a message type system set up and i am using a mysql while loop to echo out the contents from my table and am also trying to echo out the users profile image so that it appears next to each result being echoed. since this is a 2 way message system their is the photo of 'to_user_id'/recipient and 'from_user_id'/sender. this are coded as $photo and $photo2
its all working fine, the images are coming out as they should for each result being echoed by the while loop, however and for some reason, the first result is not echoing out the image, just the div container
does anyone know why this is. heres my code, thanks.
<div class="message_field">
<div class="inner_frame">
<?
$query_for_result=mysql_query("SELECT *
FROM ptb_messages
WHERE msg_id like '%".$query."%'");
$inbox_set = get_inbox();
while($data_fetch=mysql_fetch_array($query_for_result))
if (isset($_SESSION['user_id'])) {
if ($data_fetch['from_user_id'] == $_SESSION['user_id']){
{
$photo = "data/photos/{$data_fetch['from_user_id']}/_default.jpg";
if (!file_exists($photo)) {
$photo = "data/photos/0/_default.jpg";
}
$photo2 = "data/photos/{$data_fetch['to_user_id']}/_default.jpg";
if (!file_exists($photo2)) {
$photo2 = "data/photos/0/_default.jpg";
}
?>
<div class="message_bubble2">
<div class="msg_bubble_img"><img src="<?php echo $photo ?>" width="40" heigh="40" border="0"></div><?php echo "".$data_fetch['content']."";?><div class="message_bubble_tail2"></div><div class="message_bubble_tail2_shadow"></div><div class="message_bubble_tail2_shadow_bottom"></div><div class="message_bubble_tail2_outline"></div>
<div class="message_bubble_footer2">
<?php
$inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set)) { ?>
<?php echo "".$review_from.""; ?> <?
$datetime1 = new DateTime();
$datetime2 = new DateTime ($reviews['date_added']);
$interval = $datetime1->diff($datetime2);
$mdhms = explode('-',$interval->format('%m-%d-%H-%i-%s'));
$labels = Array(' months', ' days', ' hours', ' minutes', ' seconds');
$i = 0;
foreach($mdhms as $t){
if($t > 0) break;
$i+=1;
}
echo "sent by you ".$t.$labels[$i]." ago"; } ?>
</div></div>
<?
}
}else{
if (isset($_SESSION['user_id'])) {
if ($data_fetch['from_user_id'] !== $_SESSION['user_id']){
{
?>
<div class="message_bubble"><div class="msg_bubble_img2"><img src="<?php echo $photo2 ?>" width="40" heigh="40" border="0"></div><?php echo "".$data_fetch['content']."";?><div class="message_bubble_tail"></div><div class="message_bubble_tail_shadow"></div><div class="message_bubble_tail_shadow_bottom"></div><div class="message_bubble_tail_outline"></div>
<div class="message_bubble_footer">
<?php
$inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set)) { ?>
<?php echo "".$review_from.""; ?> <?
$datetime1 = new DateTime();
$datetime2 = new DateTime ($reviews['date_added']);
$interval = $datetime1->diff($datetime2);
$mdhms = explode('-',$interval->format('%m-%d-%H-%i-%s'));
$labels = Array(' months', ' days', ' hours', ' minutes', ' seconds');
$i = 0;
foreach($mdhms as $t){
if($t > 0) break;
$i+=1;
}
echo "sent from ".$inbox['from_user_id']." ".$t.$labels[$i]." ago"; } ?>
</div></div>
<? } } } } } ?>
Try forcing the order of the SELECT statement:-
<?
if (isset($_SESSION['user_id']))
{
$query_for_result=mysql_query("SELECT *, IF(from_user_id= '".mysql_real_escape_string($_SESSION['user_id'])."', 0, 1) AS ForceOrder
FROM ptb_messages
WHERE msg_id like '%".$query."%'
ORDER BY ForceOrder, ");
$inbox_set = get_inbox();
while($data_fetch=mysql_fetch_array($query_for_result))
{
if ($data_fetch['from_user_id'] == $_SESSION['user_id'])
{
{
$photo = "data/photos/{$data_fetch['from_user_id']}/_default.jpg";
if (!file_exists($photo))
{
$photo = "data/photos/0/_default.jpg";
}
$photo2 = "data/photos/{$data_fetch['to_user_id']}/_default.jpg";
if (!file_exists($photo2))
{
$photo2 = "data/photos/0/_default.jpg";
}
?>
<div class="message_bubble2">
<div class="msg_bubble_img"><img src="<?php echo $photo ?>" width="40" heigh="40" border="0"></div><?php echo "".$data_fetch['content']."";?><div class="message_bubble_tail2"></div><div class="message_bubble_tail2_shadow"></div><div class="message_bubble_tail2_shadow_bottom"></div><div class="message_bubble_tail2_outline"></div>
<div class="message_bubble_footer2">
<?php
$inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set))
{ ?>
<?php echo "".$review_from.""; ?> <?
$datetime1 = new DateTime();
$datetime2 = new DateTime ($reviews['date_added']);
$interval = $datetime1->diff($datetime2);
$mdhms = explode('-',$interval->format('%m-%d-%H-%i-%s'));
$labels = Array(' months', ' days', ' hours', ' minutes', ' seconds');
$i = 0;
foreach($mdhms as $t)
{
if($t > 0) break;
$i+=1;
}
echo "sent by you ".$t.$labels[$i]." ago";
} ?>
</div></div>
<?
}
}
else
{
if (isset($_SESSION['user_id']))
{
if ($data_fetch['from_user_id'] !== $_SESSION['user_id'])
{
{
?>
<div class="message_bubble"><div class="msg_bubble_img2"><img src="<?php echo $photo2 ?>" width="40" heigh="40" border="0"></div><?php echo "".$data_fetch['content']."";?><div class="message_bubble_tail"></div><div class="message_bubble_tail_shadow"></div><div class="message_bubble_tail_shadow_bottom"></div><div class="message_bubble_tail_outline"></div>
<div class="message_bubble_footer">
<?php
$inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set))
{ ?>
<?php echo "".$review_from.""; ?> <?
$datetime1 = new DateTime();
$datetime2 = new DateTime ($reviews['date_added']);
$interval = $datetime1->diff($datetime2);
$mdhms = explode('-',$interval->format('%m-%d-%H-%i-%s'));
$labels = Array(' months', ' days', ' hours', ' minutes', ' seconds');
$i = 0;
foreach($mdhms as $t)
{
if($t > 0) break;
$i+=1;
}
echo "sent from ".$inbox['from_user_id']." ".$t.$labels[$i]." ago";
} ?>
</div></div>
<?
}
}
}
}
}
}
?>
Related
I have a calendar that has to mark-up taken dates. For example I have 3 records in the table but only the last the most recent record added keeps displaying. How do I make all the rows show? Here is how the problem looks:
http://prntscr.com/jq25ax
And this is the query that I use to display the dates. So how do I make it show all the taken dates? Do I have to make the query in a for loop that goes until num_row?
<?php
function getCalendar($year = '', $month = '')
{
$dateYear = ($year != '') ? $year : date("Y");
$dateMonth = ($month != '') ? $month : date("m");
$date = $dateYear . '-' . $dateMonth . '-01';
$currentMonthFirstDay = date("N", strtotime($date));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN, $dateMonth, $dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7) ? ($totalDaysOfMonth) : ($totalDaysOfMonth + $currentMonthFirstDay);
$boxDisplay = ($totalDaysOfMonthDisplay <= 35) ? 35 : 42;
?>
<div id="calender_section">
<h2>
<a id="prev" href="#" onclick="return false" onmousedown="javascript:swapContent('prev')"><span class="glyphicon glyphicon-chevron-left"></span></a>
<select name="month_dropdown" class="month_dropdown dropdown"><?php
echo $this->getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php
echo $this->getYearList($dateYear); ?></select>
<a id="next" href="#" onclick="return false" onmousedown="javascript:swapContent('next')"><span class="glyphicon glyphicon-chevron-right"></span></a>
</h2>
<div id="event_list" class="none"></div>
<div id="calender_section_top">
<ul>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
$dayCount = 1;
for ($cb = 1; $cb <= $boxDisplay; $cb++) {
if (($cb >= $currentMonthFirstDay || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay - 1)) {
// Current date
$currentDate = $dateYear . '-' . $dateMonth . '-' . $dayCount;
$currentDate = strtotime($currentDate);
$eventNum = 0;
// Include db configuration file
// Get number of events based on the current date
$sql = ("SELECT COUNT(book2_id), date_from, date_to FROM booking_2 GROUP BY date_from ORDER BY COUNT(book2_id) DESC");
$result = $this->connect()->query($sql);
$eventNum = $result->num_rows;
if ($eventNum > 0) {
while ($row = $result->fetch_assoc()) {
$date_from = $row['date_from'];
$date_to = $row['date_to'];
$time_from = strtotime($date_from);
$time_fromm = idate('d', $time_from);
$time_to = strtotime($date_to);
$time_too = idate('d', $time_to);
if ($currentDate >= $time_from && $currentDate <= $time_to) {
echo '<li style="background-color:#FF3232 !important;" date="' . $currentDate . '" class="date_cell"><span>' . $dayCount . '</span>';
}
else {
echo '<li date="' . $currentDate . '" class="date_cell"><span>' . $dayCount . '</span>';
}
}
}
else {
echo '<li date="' . $currentDate . '" class="date_cell"><span>' . $dayCount . '</span>';
}
// Date cell
echo '</li>';
$dayCount++;
?>
<?php
}
else { ?>
<li><span> </span></li>
<?php
}
} ?>
</ul>
</div>
</div>
<?php
} ?>
You end the while-loop before outputting the data. Try moving the ending bracket down past the section where you echo the info, like this:
$sql = ("SELECT * FROM booking_2 ORDER BY book2_id");
$result = $this->connect()->query($sql);
$eventNum = $result->num_rows;
if($eventNum > 0){
$previousDate = 0;
while($row = $result->fetch_assoc()){
$date_from = $row['date_from'];
$date_to = $row['date_to'];
$time_from = strtotime($date_from);
$time_fromm = idate('d', $time_from);
$time_to = strtotime($date_to);
$time_too = idate('d', $time_to);
if (date("Y-m-d", $time_from) != date("Y-m-d", $previousDate)) {
if ($currentDate >= $time_from && $currentDate <= $time_to) {
echo '<li id="'.$row['book2_id'].'" style="background-color:#FF3232 !important;" date="'.$currentDate.'" class="date_cell"><span>'.$dayCount.'</span>';
}else{
echo '<li date="'.$currentDate.'" class="date_cell"><span>'.$dayCount.'</span>';
}
}
$previousDate = $time_from;
}
}else{
echo '<li date="'.$currentDate.'" class="date_cell"><span>'.$dayCount.'</span>';
}
I have this code:
<iframe src="http://voting.first-jump.com/init.php?a=g&g=1516932783462&m=1&n=5&s=64&f=3.png&f_a=&f_b=&f_c=" allowtransparency="true" hspace="0" vspace="0" marginheight="0" marginwidth="0" frameborder="0" height="84" scrolling="no" width="323"></iframe>
I have added a $post_id in the src string (to make a unique frame load for every post a person made on my social network) so, now it's like this:
<iframe src="http://voting.first-jump.com/init.php?a=g&g=1516932126956&m=10&n=5&s=20&f=3.png&f_a=&f_b=&f_c= <?php echo $post_id; ?>" allowtransparency="true" hspace="0" vspace="0" marginheight="0" marginwidth="0" frameborder="0" height="33" scrolling="no" width="103"></iframe>
I don't know what I am doing wrong, because the $post_id is not working.
Thanks!
Edited: This is the hole php code:
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>
<style type="text/css">
* {
font-size: 12px;
font-family: Arial, Helvetica, Sans-serif;
}
</style>
<?php
require 'config/config.php';
include("includes/classes/User.php");
include("includes/classes/Post.php");
include("includes/classes/Notification.php");
if (isset($_SESSION['username'])) {
$userLoggedIn = $_SESSION['username'];
$user_details_query = mysqli_query($con, "SELECT * FROM users WHERE username='$userLoggedIn'");
$user = mysqli_fetch_array($user_details_query);
}
else {
header("Location: register.php");
}
?>
<script>
function toggle() {
var element = document.getElementById("comment_section");
if(element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
</script>
<?php
//Get id of post
if(isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
}
$user_query = mysqli_query($con, "SELECT added_by, user_to FROM posts WHERE id='$post_id'");
$row = mysqli_fetch_array($user_query);
$posted_to = $row['added_by'];
$user_to = $row['user_to'];
if(isset($_POST['postComment' . $post_id])) {
$post_body = $_POST['post_body'];
$post_body = mysqli_escape_string($con, $post_body);
$date_time_now = date("Y-m-d H:i:s");
$insert_post = mysqli_query($con, "INSERT INTO comments VALUES ('', '$post_body', '$userLoggedIn', '$posted_to', '$date_time_now', 'no', '$post_id')");
if($posted_to != $userLoggedIn) {
$notification = new Notification($con, $userLoggedIn);
$notification->insertNotification($post_id, $posted_to, "comment");
}
if($user_to != 'none' && $user_to != $userLoggedIn) {
$notification = new Notification($con, $userLoggedIn);
$notification->insertNotification($post_id, $user_to, "profile_comment");
}
$get_commenters = mysqli_query($con, "SELECT * FROM comments WHERE post_id='$post_id'");
$notified_users = array();
while($row = mysqli_fetch_array($get_commenters)) {
if($row['posted_by'] != $posted_to && $row['posted_by'] != $user_to
&& $row['posted_by'] != $userLoggedIn && !in_array($row['posted_by'], $notified_users)) {
$notification = new Notification($con, $userLoggedIn);
$notification->insertNotification($post_id, $row['posted_by'], "comment_non_owner");
array_push($notified_users, $row['posted_by']);
}
}
echo "<p>Comment Posted </p>";
}
?>
<form action="comment_frame.php?post_id=<?php echo $post_id; ?>" id="comment_form" name="postComment<?php echo $post_id; ?>" method="POST">
<textarea name="post_body"></textarea>
<input type="submit" name="postComment<?php echo $post_id; ?>" value="Post">
</form>
<iframe src="http://voting.first-jump.com/init.php?a=g&g=1516932126956&m=10&n=5&s=20&f=3.png&f_a=&f_b=&f_c= <?php echo $post_id; ?>" allowtransparency="true" hspace="0" vspace="0" marginheight="0" marginwidth="0" frameborder="0" height="33" scrolling="no" width="103"></iframe>
<!-- Load comments -->
<?php
$get_comments = mysqli_query($con, "SELECT * FROM comments WHERE post_id='$post_id' ORDER BY id ASC");
$count = mysqli_num_rows($get_comments);
if($count != 0) {
while($comment = mysqli_fetch_array($get_comments)) {
$comment_body = $comment['post_body'];
$posted_to = $comment['posted_to'];
$posted_by = $comment['posted_by'];
$date_added = $comment['date_added'];
$removed = $comment['removed'];
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_added); //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 == 1)
$time_message = $interval->y . " year ago"; //1 year ago
else
$time_message = $interval->y . " years ago"; //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";
}
}
$user_obj = new User($con, $posted_by);
?>
<div class="comment_section">
<img src="<?php echo $user_obj->getProfilePic();?>" title="<?php echo $posted_by; ?>" style="float:left;" height="30">
<b> <?php echo $user_obj->getFirstAndLastName(); ?> </b>
<?php echo $time_message . "<br>" . $comment_body; ?>
<hr>
</div>
<?php
}
}
else {
echo "<center><br><br>No reviews</center>";
}
?>
</body>
</html>
There space between your code.
Here is your mistake
f_c= <?php echo $post_id; ?>. The space would be convert into %20 in the url.
So it would be look like this. f_c=%20<?php echo $post_id; ?>
You can try this one
<iframe src="http://voting.first-jump.com/init.php?a=g&g=1516932126956&m=10&n=5&s=20&f=3.png&f_a=&f_b=&f_c=<?php echo $post_id; ?>" allowtransparency="true" hspace="0" vspace="0" marginheight="0" marginwidth="0" frameborder="0" height="33" scrolling="no" width="103"></iframe>
I am working on a calendar, using my own code, I can current only get dates to show as booked if they are within the same month.
How would I get things to work if dates go across more than a single month?
These are the main variables that setup the calendar (which come before my while loop):
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$dayMiniLabels = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
$monthLables = array("January","February","March","April","May","June","July","August","September","October","November","December");
//max values
$maxDays = 7;
$maxMonths = 12;
//stats
$forceMonth = $_GET['m'];
$forceYear = $_GET['y'];
$todayDate = date("d-m-Y");
$todayDate = date("d-m-Y", strtotime($todayDate));
$explodeToday = explode("-", $todayDate);
$currentDay = $explodeToday[0];
if(isset($forceMonth)) {
$currentMonth = $forceMonth;
} else {
$currentMonth = $explodeToday[1];
};
if(isset($forceYear)) {
$currentYear = $forceYear;
} else {
$currentYear = $explodeToday[2];
};
$currentDate = strtotime("01-$currentMonth-$currentYear");
$prevMonth = sprintf("%02d", $currentMonth - 1);
$nextMonth = sprintf("%02d", $currentMonth + 1);
$prevYear = sprintf("%02d", $currentYear - 1);
$nextYear = sprintf("%02d", $currentYear + 1);
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
$firstDayofMonth = date("D", $currentDate);
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth;
//database values
$bookedStart = array();
$bookedEnd = array();
$bookedUser = array();
if($getBookings = $con->prepare("SELECT userID,bookingStart,bookingEnd FROM bookings WHERE machineID=?")) {
$getBookings->bind_param("i", $_GET['id']);
if($getBookings->execute()) {
$getBookings->bind_result($bookingUserID,$bookingStart,$bookingEnd);
while($getBookings->fetch()) {
array_push($bookedStart, $bookingStart);
array_push($bookedEnd, $bookingEnd);
array_push($bookedUser, $bookingUserID);
};
};
};
$getBookings->close();
//counters
$daysIntoMonth = 0;
$dayCounter = 0;
$startMonth = 0;
This is the current display code for the calendar (the stuff that prints the calendar):
<table class="full grid dayLabels">
<tr>
<?php
foreach($dayLabels as $day) {
echo '<td class="day"><p>' .$day. '</p></td>';
};
?>
</tr>
</table>
<table id="calendar" class="full grid calendar">
<?php
while($daysIntoMonth < $daysInMonth) {
//days into month
$daysIntoMonth++;
$temp_intoMonth = sprintf("%02d", $daysIntoMonth);
$daysIntoMonth = $temp_intoMonth;
//days into week
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
//current calendar date
$calDate = date('d-m-Y', strtotime($daysIntoMonth. '-' .$currentMonth. '-' .$currentYear));
$calTime = strtotime($calDate);
$todaysNumber = date('w', $timeCal);
if($dayCounter == 1) {
echo '<tr>';
};
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td class="padding"></td>';
$startMonth++;
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
};
};
if($startKey = in_array($calDate, $bookedStart, true)) {
$booked = true;
echo '
<td class="booked">
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
} else if(in_array($calDate, $bookedEnd, true)) {
$booked = false;
echo '
<td class="booked">
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
} else if($booked == true) {
echo '
<td class="booked">
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
} else {
echo '
<td>
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
};
if($dayCounter == $maxDays) {
echo '</tr>';
$dayCounter = 0;
};
};
?>
</table>
I current look for a start date to set the variable booked variable as true until it comes across an end date. This means that the calendar will only work for dates that are contained within the same month...
How would I go about making the dates work across months?
I ended up completely reworking my calendar system to get this to work the way how I wanted it to:
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$dayMiniLabels = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
$monthLables = array("January","February","March","April","May","June","July","August","September","October","November","December");
$forceMonth = $_GET['m'];
$forceYear = $_GET['y'];
$currentDate = date("Y-m-d");
$explodeDate = explode("-", $currentDate);
//Currents
if(isset($forceMonth)) {
if(strlen($forceMonth) == 1) {
$forceMonth = sprintf("%02d", $forceMonth);
};
$currentMonth = $forceMonth;
} else {
$currentMonth = date("m");
};
if(isset($forceYear)) {
if(strlen($forceYear) == 2) {
$dt = DateTime::createFromFormat('y', $forceYear);
$forceYear = $dt->format('Y');
};
$currentYear = $forceYear;
} else {
$currentYear = date("Y");
};
//variables
$monthStart = date($currentYear. '-' .$currentMonth. '-01');
$monthEnd = date($currentYear. '-' .$currentMonth. '-t');
$prevMonth = sprintf("%02d", $currentMonth - 1);
$nextMonth = sprintf("%02d", $currentMonth + 1);
$prevYear = sprintf("%02d", $currentYear - 1);
$nextYear = sprintf("%02d", $currentYear + 1);
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
$firstDayofMonth = date("D", strtotime("01-$currentMonth-$currentYear"));
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth;
if($firstDayofMonth == 0) {
$firstDayofMonth = 7;
};
$bookings = array();
$s = new DateTime($monthStart);
$e = new DateTime("$monthEnd + 1 days");
$oneday = new DateInterval('P1D');
$dp = new DatePeriod($s, $oneday, $e);
foreach ($dp as $d) {
$bookings[$d->format('Y-m-d')] = '';
};
$sql = "SELECT userID
, bookingStart
, bookingEnd
FROM bookings
WHERE machineID = ?
AND bookingStart < ?
AND bookingEnd > ?";
$getBookings = $con->prepare($sql);
$getBookings->bind_param('iss', $_GET['id'], $monthEnd, $monthStart);
$getBookings->execute();
$getBookings->bind_result($uid, $bstart, $bend);
while ($getBookings->fetch()) {
$s = new DateTime(max($bstart, $monthStart));
$e = new DateTime(min($bend, $monthEnd));
$e->modify('+1 day');
$dp = new DatePeriod($s, $oneday, $e);
foreach ($dp as $d) {
$bookings[$d->format('Y-m-d')] = $uid;
};
};
//counters
$dayCount = 0;
$startMonth = 0;
$calDate = 0;
<table class="full grid dayLabels">
<tr>
<?php
foreach($dayLabels as $day) {
echo '<td class="day"><p>' .$day. '</p></td>';
};
?>
</tr>
</table>
<table id="calendar" class="full grid calendar">
<?php
foreach($bookings as $date) {
$dayCount++;
$calDate++;
$calDate = sprintf("%02d", $calDate);
if($dayCount == 1) {
echo '<tr>';
};
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td class="padding"></td>';
$startMonth++;
$dayCount++;
$temp_dayCount = sprintf("%02d", $dayCount);
$dayCount = $temp_dayCount;
};
};
if($date != "") {
if($getUserName = $con->prepare("SELECT userFirst,userLast,userEmail FROM users WHERE userID=?")) {
$getUserName->bind_param("i", $date);
$getUserName->execute();
$getUserName->bind_result($userFirst,$userLast,$userEmail);
while($getUserName->fetch()) {
echo '
<td class="booked">
<p>' .$calDate. '</p>
<p>' .$userFirst. ' ' .$userLast. '</p>
</td>
';
};
};
$getUserName->close();
} else {
echo '
<td>
<p>' .$calDate. '</p>
';
if(isset($_SESSION['userID']) && $_SESSION['userPerms'] > 0) {
echo '
<a class="bookNow"></a>
<form class="book" method="post" action="./action.php?a=book">
<input name="userID" type="hidden" value="' .$_SESSION['userID']. '" required />
<input name="machineID" type="hidden" value="' .$id. '" required />
<div class="options">
<a class="fa fa-close"></a>
</div>
<p>Start Date</p>
<input name="startDate" type="text" value="' .$calDate. '-' .$currentMonth. '-' .$currentYear. '" autofocus required />
<p>End Date</p>
<input name="endDate" type="text" value="' .$calDate. '-' .$currentMonth. '-' .$currentYear. '" required />
<p>Project Number</p>
<input name="projectNumber" type="number" placeholder="Project Number" required />
<button class="confirm" type="submit">Submit</button>
</form>
';
};
echo '
</td>
';
};
if($dayCount == 7) {
echo '</tr>';
$dayCount = 0;
};
};
?>
</table>
I have php to display the calender and another php to check database to see bookings, If there is a booking on certain day it displays "Booked". In database i have column for date of booking and title. How could i make it to display Title from the database instead of "Booked"?
This is to display calender.
<?php
$monthNames = Array("January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December");
?>
<?php
if (!isset($_REQUEST["month"]))
$_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"]))
$_REQUEST["year"] = date("Y");
?>
<?php
$cMonth = $_REQUEST["month"];
$cYear = $_REQUEST["year"];
$prev_year = $cYear;
$next_year = $cYear;
$prev_month = $cMonth-1;
$next_month = $cMonth+1;
if ($prev_month == 0 )
{
$prev_month = 12;
$prev_year = $cYear - 1;
}
if ($next_month == 13 )
{
$next_month = 1;
$next_year = $cYear + 1;
}
require("BookingsDB.php");
$myBookingsDB = new BookingsDB();
$bookings = $myBookingsDB->getMonthlyBookings($cMonth,$cYear);
?>
<div align="left">
<table width="400" border="5" align="left" id="calendar">
<tr align="center">
<td bgcolor="#999999" style="color:#FFFFFF"><table width="100%" border="0"
cellspacing="0" cellpadding="0">
<tr>
<td width="50%" align="left"><a href="<?php echo $_SERVER["PHP_SELF"]
. "?month=". $prev_month . "&year=" . $prev_year; ?>"
style="color:#FFFFFF">Previous</a></td>
<td width="50%" align="right"><a href="<?php echo $_SERVER["PHP_SELF"]
. "?month=". $next_month . "&year=" . $next_year; ?>"
style="color:#FFFFFF">Next</a></td>
</tr>
</table></td>
</tr>
<tr>
<td align="center"><table width="100%" border="2" cellpadding="2"
cellspacing="2">
<tr align="center">
<td colspan="7" bgcolor="#999999" style="color:#FFFFFF"><strong> <?php
echo $monthNames[$cMonth-1].' '.$cYear; ?></strong></td>
</tr>
<tr>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>S</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>M</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>W</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>F</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>S</strong></td>
</tr>
<?php
require("connection.php");
$con=mysqli_connect("$mysql_host","$mysql_user","$mysql_password","$mysql_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "select activityEvent.activityTitle from activityEvent";
$result = mysqli_query($con,$sql);
$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$timestamp);
$thismonth = getdate ($timestamp);
$startday = $thismonth['wday'];
$today = getdate();
for ($i=0; $i<($maxday+$startday); $i++)
{
if(($i % 7) == 0 )
{
echo "<tr> ";
}
if($i < $startday)
{
echo "<td></td> ";
}
else
{
$day = $i - $startday + 1;
$thisDate = new DateTime("$cYear-$cMonth-$day");
$jsEvent[] = "document.getElementById('trigger" . $i . "').onclick = function() {showForm()};";
echo "<td align='center' valign='middle' height='20px'><a href='#' id='trigger" . $i . "'>". ($i - $startday + 1) . "</a>";
foreach ($bookings as $bookingDate)
{
if ($thisDate==$bookingDate)
{
echo "Booked";
while($row = mysqli_fetch_array($result))
{
echo $sql= "select activityEvent.activityTitle from activityEvent";
}
}
}
echo "</td>";
}
if(($i % 7) == 6 )
{
echo "</tr> ";
}
}
mysqli_close($con);
?>
<script type="text/javascript">
<?php foreach($jsEvent as $event)
{
echo $event;
}
?>
function showForm(){
document.getElementById('timeslots').style.display="block";
};
</script>
</table></td>
</tr>
</table>
This PHP checks booked dates in the database.
<?php
class BookingsDB
{
private $bookings = array();
private $con;
public function BookingsDB()
{
require("connection.php");
$this->con = mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
}
public function getMonthlyBookings($thisMonth,$thisYear)
{
$sql = "SELECT date,activityTitle FROM activityEvent WHERE YEAR(date) = $thisYear AND MONTH(date) = $thisMonth";
$result = mysqli_query($this->con,$sql);
while($row=mysqli_fetch_array($result))
{
$thisBooking = $row['date'];
$thisBookingDateTime = new DateTime($thisBooking);
array_push($this->bookings,$thisBookingDateTime);
}
return $this->bookings;
}
public function close()
{
mysqli_close($this->con);
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.red
{
color: red
}
.green
{
background-color: aquamarine;
}
table
{
text-align: center;
}
td
{
height: 60px;
width: 100px;
}
.opcity
{
background-color: rgba(0,0,0,.2);
}
</style>
</head>
<body>
<?php
$Cur_day = date('d');
$Cur_Month = date('m');
$Cur_Year = date('Y');
$op = '';
if (isset($_REQUEST['month']) || isset($_REQUEST['year']) && isset($_REQUEST['stday']))
{
$Mo = $_REQUEST['month'];
$Year = $_REQUEST['year'];
$query_date = $Year . '-' . $Mo . '-21';
if (isset($_REQUEST['opra']))
{
$str = $_REQUEST['opra'];
if ($str == 'iny')
{
$op = '+1 year';
}
if ($str == 'dey')
{
$op = '-1 year';
}
if ($str == 'inm')
{
$op = '+1 month';
}
if ($str == 'dem')
{
$op = '-1 month';
}
if ($str == 'dem' || $str == 'inm' || $str == 'dey' || $str == 'iny')
{
$query_date1 = date('Y-m-01', strtotime($op, strtotime($query_date)));
$lastDay = date('t', strtotime($op, strtotime($query_date)));
$year = date('Y', strtotime($op, strtotime($query_date)));
$month = date('n', strtotime($op, strtotime($query_date)));
$Month_Name = date('M', strtotime($op, strtotime($query_date)));
$pre_month = date('t', strtotime('-1 month', strtotime($year . '-' . $month . '-21')));
}
if ($str == 'No')
{
$query_date1 = date('Y-m-01', strtotime($query_date));
$lastDay = date('t', strtotime($query_date));
$year = date('Y', strtotime($query_date));
$month = date('n', strtotime($query_date));
$Month_Name = date('M', strtotime($query_date));
$pre_month = date('t', strtotime('-1 month', strtotime($year . '-' . $month . '-21')));
}
}
?>
<input type="hidden" name="txt_year" id="txt_year1" value="<?php echo $year; ?>">
<input type="hidden" name="txt_month1" id="txt_month1" value="<?php echo $month; ?>">
<table border="1">
<tr>
<td><<</td>
<td><</td>
<td colspan="3"><?php echo $Month_Name . "-" . $year; ?></td>
<td>></td>
<td>>></td>
</tr>
<tr>
<?php
echo '<tr>';
for ($i = 1; $i <= 7; $i++)
{
if ($_REQUEST['stday'] == 'Sun')
{
$j_val = 0;
echo "<th>" . date("l", gmmktime(0, 0, 0, 11, $i, 2015));
echo '</th>';
} else
{
$j_val = 1;
echo "<th>" . date("l", gmmktime(0, 0, 0, 6, $i, 2015));
echo '</th>';
}
}
echo '</tr>';
?>
</tr>
<?php
$Conn = new mysqli("localhost", "root", "", "demo");
$firstDays = mktime(0, 0, 0, date($month), 1, date($year));
$weekday = date('N', $firstDays);
$i = 0;
$j = 0;
$date = 1;
$Count = 0;
$Count1 = 0;
$next_mo = 1;
function Holiday($day1, $month1, $year1)
{
global $Conn;
$result = $Conn->query("SELECT * FROM holiday");
while ($row = mysqli_fetch_assoc($result))
{
if ($row['day'] == $day1 && $row['month'] == $month1 && $row['year'] == $year1)
{
return $row['title'] . "<br>";
}
}
}
for ($i = 0; $i < 6; $i++)
{
echo '<tr>';
$pre_month = $pre_month - ($weekday - $j_val);
for ($j = $j_val; $j <= 6 + $j_val; $j++)
{
if ($Count < $weekday - $j_val && ($weekday != 7 || $_REQUEST['stday'] == 'Mon'))
{
echo "<td class='opcity'>" . ( ++$pre_month) . "</td>";
$Count++;
} else
{
if ($date <= $lastDay)
{
if ($Cur_day == $date && $Cur_Month == $month && $Cur_Year == $year)
{
if (date("l", gmmktime(0, 0, 0, $month, $date, $year)) == 'Sunday')
{
echo '<td class = "green red">';
echo Holiday($date, $month, $year);
} else
{
echo '<td class = "green">';
echo Holiday($date, $month, $year);
}
} else
{
if (date("l", gmmktime(0, 0, 0, $month, $date, $year)) == 'Sunday')
{
echo '<td class = "red">';
echo Holiday($date, $month, $year);
} else
{
echo '<td >';
echo Holiday($date, $month, $year);
}
}
echo $date;
echo '</td>';
$date++;
if ($date == $lastDay)
{
$i = 7;
}
} else
{
echo "<td class='opcity'>" . $next_mo++ . "</td>";
}
}
}
echo '</tr>';
}
}
?>
</table>
</body>
</html>
//<Ajax_cal.php
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="JS/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function Caleonload()
{
$('#month').val('<?php echo date("n"); ?>');
$('#year').val('<?php echo date('Y'); ?>');
Opretion('No');
}
function Cal(month)
{
$('#month').val(month);
Opretion('No');
}
function Cal1(year)
{
$('#year').val(year);
Opretion('No');
}
function Opretion(Op)
{
var st_day = $('input[type="radio"][class="rd_sun_mon"]:checked').val();
var Mo = $('#month').val();
var Year = $('#year').val();
var Op1 = Op;
$.post("AJAX/Ajax_Cal.php",
{
month: Mo,
year: Year,
opra: Op1,
stday: st_day
},
function (data)
{
$('#Show_Cal').html(data);
var txt_year = $('#txt_year1').val();
$("#year").html('');
for (var y = parseInt(txt_year) - 5; y < parseInt(txt_year) + 5; y++)
{
$("#year").append('<option value="' + y + '">' + y + '</option>');
}
$('#year').val(txt_year);
$('#month').val($('#txt_month1').val());
}
);
}
function incyear()
{
Opretion('iny');
}
function deyear()
{
Opretion('dey');
}
function incmonth()
{
Opretion('inm');
}
function demonth()
{
Opretion('dem');
}
</script>
</head>
<body onload="Caleonload()">
<select name="month" id="month" onchange="Cal(this.value)" size="1">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="year" id="year" onchange="Cal1(this.value)" size="1">
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
Starting Day :
<input type="radio" name="rd_sun_mon" class="rd_sun_mon" value="Sun" checked="" onchange="Opretion('No')">Sunday
<input type="radio" name="rd_sun_mon" class="rd_sun_mon" value="Mon" onchange="Opretion('No')">Monday
<div id="Show_Cal"></div>
</body>
</html>
DATA BASE PHP MY ADDMIN:
CREATE TABLE IF NOT EXISTS holiday (
id int(5) NOT NULL AUTO_INCREMENT,
day int(4) NOT NULL,
month int(4) NOT NULL,
year int(6) NOT NULL,
title varchar(20) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
I think your problem is that is that you need to put the format in order to compare two Datetime :
if ($thisDate->format('Y-m-d')==$bookingDate->format('Y-m-d'))
{
echo "Booked";
....
}
In addition to #SimonGuichard's answer, I suggest that you return an associative array from the getMonthlyBookings function that contains both the date and the activityTitle. This way, you wouldn't have to select the title from the database again when it needs to be displayed.
public function getMonthlyBookings($thisMonth,$thisYear) {
$sql = "SELECT date,activityTitle FROM activityEvent WHERE YEAR(date) = $thisYear AND MONTH(date) = $thisMonth";
$result = mysqli_query($this->con,$sql);
while($row=mysqli_fetch_array($result)) {
$this->bookings[] = array('date'=>new DateTime($row['date']), 'activityTitle'=>$row['activityTitle']);
}
return $this->bookings;
}
Then in the script that displays the calendar, you should modify it this way:
$day = $i - $startday + 1;
$thisDate = new DateTime("$cYear-$cMonth-$day");
$jsEvent[] = "document.getElementById('trigger" . $i . "').onclick = function() {showForm()};";
echo "<td align='center' valign='middle' height='20px'><a href='#' id='trigger" . $i . "'>". ($i - $startday + 1) . "</a>";
// $bookings is an associative array of the form array('0'=>array('date'=>'date_value', 'activityTitle'=>'activityTitle_value'))
foreach ($bookings as $key => $value) {
if ($thisDate->format('Y-m-d') === $value['date']->format('Y-m-d')) {
// this prints out the activity title
echo $value['activityTitle'];
}
}
I am having a problem. I can't display the weekdays.
So when I click next it should display the week for nextweek displaying Monday to Friday.
And when I click previous it should display lastweek Monday to Friday
here's my code
in controller
<?php
public function calendar($dt) {
// = date("Y/m/d");
$beginDate = $dt;
$endDate = date("Y-m-d", strtotime($dt . "+6 days"));
$posts = $this->Post->getWeekPosts($beginDate, $endDate);
$members = $this->Post->PostgetUniqueMembers($posts);
// $week = $this->Post->weekNo($beginDate, $endDate);
$this->set("posts", $posts);
$this->set("members", $members);
$this->set("begin", $beginDate);
// $this->set("week", $week);
}
in view
<div id="content">
<span id="calendar-week">
<!-- <h2> week <?php echo $week; ?> <?php echo date("F Y", strtotime($begin)) ?> </h2>-->
<h2> week <?php echo date("F Y", strtotime($begin)) ?> </h2>
Previous |
Next
</span>
<div id="calendar">
<table>
<tr id="calendar-names"><!-- member names -->
<td> </td>
<?php foreach ($members as $member) { ?>
<td><p><?php echo $member ?></p></td>
<?php } ?>
</tr>
<?php
foreach ($posts as $key => $post) {
?>
<tr>
<td class="calendar-background-days"><p class="calendar-days"><?php echo date("D", strtotime($key)) ?></p></td>
<?php foreach ($members as $memberKey => $member) { ?>
<td class="calendar-background-content">
<?php foreach ($post as $contentKey => $content) { ?>
<?php if ($contentKey == $memberKey) { ?>
<?php foreach ($content as $c) { ?>
<p><?php echo $c['Post']['content'] ?></p>
<?php } ?>
<?php
}
}
?>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
</div>
</div>
in model
public function getWeekPosts($begin, $end) {
$res = $this->find("all", array("order" => array('deadline', 'member_id'), "conditions" => "deadline BETWEEN '" . $begin . "' AND '" . $end . "'"));
$res = $this->formatWeekPosts($begin, $res);
return $res;
}
public function formatWeekPosts($begin, $res) {
$dt = array();
for ($i = 0; $i < 6; $i++) {
$dt[] = date("Y-m-d", strtotime($begin . "+ " . $i . " days"));
}
$members = array();
$pastMember = "";
foreach ($res as $r) {
if ($pastMember != $r['Post']['member_id']) {
$members[] = $r['Post']['member_id'];
$pastMember = $r['Post']['member_id'];
}
}
$posts = array();
foreach ($dt as $d) {
foreach ($res as $r) {
if ($r['Post']['deadline'] == $d) {
$posts[$d][] = $r;
}
}
}
$sortedPosts = array();
foreach ($members as $member) {
foreach ($posts as $key => $postDate) {
foreach ($postDate as $key2 => $p) {
if ($p["Post"]['member_id'] == $member) {
$sortedPosts[$key][$p["Post"]['member_id']][$key2] = $p;
}
}
}
}
ksort($sortedPosts);
return $sortedPosts;
}
public function PostgetUniqueMembers($posts) {
$members = array();
foreach ($posts as $post) {
foreach ($post as $p) {
$members[$p[key($p)]["Post"]["member_id"]] = $p[key($p)]["Member"]['username'];
}
}
return $members;
}