Extending calendar functionality to accept years - php

I'm working on an event scheduler site and I am currently stuck as I'm using a Months table (with id & month as the headers) to group my results by month. Due to this, if I try to schedule an event for January 2016, it successfully puts it into the month I choose as intended, but understandably puts it into 2015.
I'm looking to get some help on extending this beyond the end of the current year and adding functionality for different years.
I would happily use another method than using my current table setup, so any tips or suggestions would be appreciated.
Current code is as follows:
<?php include 'includes/connect.php';
include 'includes/header.php';
$curMonth = date("n"); ?>
<b>Upcoming Trip Information:</b><br><br>
<?php
$res = mysql_query("SELECT * FROM months ORDER BY id");
while ($rows = mysql_fetch_array($res)) {
if($rows['id'] >= $curMonth ){
$monthname = $rows['month']; ?>
<table cellpadding="0" cellspacing="3" width="100%">
<tr>
<td>
<?php
$tid = $_GET['transporter'];
$check = mysql_query("SELECT * FROM trips WHERE monthname(start_date) = '" . $rows['month'] . "' AND tid = '$tid'");
$check = mysql_num_rows($check);
if ($check < 1) {
echo "";
} else { ?> <h2><?php echo $monthname; ?><?php } ?></h2></td></tr> <tr> <?php $cmonth = date('F');
$tid = $_GET['transporter'];
$res1 = mysql_query("SELECT * FROM trips WHERE monthname(start_date) = '$monthname' ORDER BY start_date");
while ($rows = mysql_fetch_array($res1)) {
$trid = $rows['trid'];
$trip_start = $rows['trip_start'];
$trip_end = $rows['trip_end'];
$start_date = $rows['start_date'];
$end_date = $rows['end_date'];
$colour = $rows['colour'];
$stime = strtotime($start_date);
$startt = date("l jS", $stime);
$etime = strtotime($end_date);
$endt = date("l jS", $etime); ?>
<td valign="middle" style="height: 100px; background-color: #4b99ed; text-align: center;">
<div style="font-size: 17px; color: #ffffff;"><?php echo $trip_start; ?> to <?php echo $trip_end; ?></div>
<div style="font-size: 15px; color: #ffffff;"><?php echo $startt; ?> - <?php echo $endt; ?></div>
</td>
<?php } } } ?>
</tr>
</table> <?php include 'includes/footer.php'; ?>
If possible I would like to maintain the results layout..

You could try, instead of using a months table, using the start_date column of your trips table.
Try changing your query:
SELECT trips.*, DATE_FORMAT('%M, %Y', start_date) as `dt`
FROM trips
WHERE tid = '$tid' /* This is bad, please prepare or escape your variables*/
ORDER BY `dt` ASC
You then won't have to do the first query to get all the months and loop through them. If you must have empty containers for each month, try using that query, but loop through a PHP-generated array of months to display.

Related

How to output average rating with stars?

I have managed to output the average rating in a number format, but i would like to output it by using the star method as well.
This is my code so far that outputs the average rating by using numbers;
<?php
$sql = "
SELECT round(avg(`rate`),2) AS `average_rate`, count(`rate`) AS `num_of_rating`
FROM tbl_rating
WHERE hotel_id = '$id' ";
$query = mysqli_query($con,$sql);
$rating = mysqli_fetch_assoc($query);
?>
<div>
<h4 style="color: #1478FF; font-size:30px; font-family: " > <?php echo $rating['average_rate']; ?> Avergae rating </h4>
</div>
For instance;Stars
Please give this a try:
<?php
$sql = "
SELECT round(avg(`rate`),2) AS `average_rate`, count(`rate`) AS `num_of_rating`
FROM tbl_rating
WHERE hotel_id = '$id' ";
$query = mysqli_query($con,$sql);
$rating = mysqli_fetch_assoc($query);
?>
<div>
<h4 style="color: #1478FF; font-size:30px; font-family: " > <?php echo $rating['average_rate']; ?> Average rating </h4>
<?php
$limit = floor($rating['average_rate']);
$remainder = $rating['average_rate'] % 1.0;
for( $i = 0; $i<$limit; $i++ ) {
echo ("<img src=\"\\images\\fullstar.jpg\" />");
}
if ($remainder >= 0.5) echo ("<img src=\"\\images\\halfstar.jpg\" />");
?>
</div>
I'm not sure this will work. I have no way of testing the code, I'm a C# and ColdFusion developer. This is what a few minutes on Google gave me.
To make this work, you need images of a full star called fullstar.jpg and of a half start called halfstar.jpg. They both need to be in a folder names images in your project root.

create table with loop in Php

What I want is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
Now I am using hard code and the result have to looks like this
So, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
It has to move to next row.
Because I am referring to my db, so I am using loop to create the table, and when I doing that way, I am getting this result....
The result will keep showing until the end in the left side. Thats very hard to read for report purposes. I wanted the result looks like the first figure that I've uploaded.
Here is what I am doing now:
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
you need to add td dynamically within a table for each day report ( data should be grouped by date).
You just need to float each table with the float:left css property and some percentage based on the number of tables you want on the same row. In this case, 33% will do. Take a look at this codepen: http://codepen.io/anon/pen/EgXqPk
The magic happens on:
.tg {
width: 33%;
float:left;
}
you can try i hope this perfect for you to draw a table using PHP Loop.
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 10; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 10; $col++) {
$p = $col * $row;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>

Populating an HTML table with MySQL data, linked by calendar date

I am using the code below to generate a simple HTML table that displays the next 90 calendar days. Each day is a row in this simple table.
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td></tr>\n";
}
echo "</table>";
Also, I have a MySQL table with the following fields:
event varchar(1000)
datescheduled date
How can I make a second column in the aforementioned HTML table, containing "event" from the MySQL table, matched by date?
This can be tackled in numerous ways. Consider this example:
PHP
<?php
$con = mysqli_connect("localhost","dbuser","dbpass","database");
$query = mysqli_query($con, "SELECT * FROM event");
// First build the array of events, put the dates in keys, then the values as events
$events = array();
while($result = mysqli_fetch_assoc($query)) {
$events[$result['datescheduled']] = $result['event'];
}
?>
// Structure should be something like this:
Array
(
[2014-05-02] => Day of lorem
[2014-06-02] => Day of ipsum
[2014-07-02] => Day of days
)
HTML
<!-- the compare selected values on the current loop, check its keys -->
<?php $now = time(); ?>
<table border="1" cellpadding="10">
<?php for($i=0;$i<90;$i++): ?>
<?php $thisDate = date("Y-m-d", $now + ($i*86400)); ?>
<tr>
<td><?php echo $thisDate; ?></td>
<td><?php echo array_key_exists($thisDate, $events) ? $events[$thisDate] : ''; ?></td>
</tr>
<?php endfor; ?>
</table>
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td>";
$result_set = mysql_query("SELECT event FROM eventTable WHERE datescheduled = STR_TO_DATE('{$thisDate}','%d/%m/%Y')'",$connection);
$result = mysql_fetch_assoc($result_set);
echo "<td>{$result['event']}</td></tr>\n";
}
echo "</table>";
Its worth noting that you will need to use a string to date function in mysql depending on how the date is stored.
Edit: in case you need further hand holding, here is the STR_TO_DATE function done for you.
STR_TO_DATE('{$thisDate}','%d/%m/%Y')
I have edited my code above to reflect this as to not strain your brain.
Even tossed in some screenshots of the table and the output, just because you were kind of an ass in your comment. With 5 years of experience i would have thought you would know how to echo out a simple table like this, or at the very least, have a little common courtesy when someone tries to help you.

MYSQL ordering columns in my query

I have been working on trying to get a bunch of data to work in a table structure displayed neatly using PHP, and I must say I am having a difficult time. I have finally been able to call the columns so that in case I add a field it will always add it in my table, and I hope for this to be very easily managed. However, when I initially set up the table, I put it in a random order. Now when I come use the DESCRIBE table it gives them to me in exact order, and I cannot find a way to organize them better. It would not make sense to say have month/year at the end of the database for my form that I have.
<?php
require 'connect.php';
?>
<h3>Monthly Finances | Add New Month </h3>
<table border="1" bordercolor ="#000000">
<tr>
<?php
$columns = "DESCRIBE `month` ";
if($query_run_columns = mysql_query($columns)){
$columnNames = array();
while($column = mysql_fetch_assoc($query_run_columns)){
echo '<th>'.$column['Field'].'</th>';
}
}else{
echo'sql error';
}
?>
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
while($row = mysql_fetch_assoc($query_run)){
$rent = $row['rent'];
$electric = $row['electric'];
$cable = $row['cable'];
$cellphone = $row['cellphone'];
$renters = $row['renters'];
$month = $row['month'];
$year = $row['year'];
echo '<tr>';
echo '<td align="center">'.$month.'</td>';
echo '<td algin="center">'.$year.'</td>';
echo '<td align="center">'.$rent.'</td>';
echo '<td align="center">'.$electric.'</td>';
echo '<td align="center">'.$cable.'</td>';
echo '<td align="center">'.$cellphone.'</td>';
echo '<td align="center">'.$renters.'</td>';
echo '</tr>';
}
}else{
echo 'query error';
}
?>
<br>View by month
</table>
<form action="index.php" method="GET">
<select name="months" value="all">
<?php
$gathermonths = "SELECT `month`, `year` FROM `month";
if($query_month_selector = mysql_query($gathermonths)){
while($month_row = mysql_fetch_assoc($query_month_selector)){
$month = $month_row['month'];
$year = $month_row['year'];
echo '<option value="'.$month.' '.$year.'">' .$month.' '.$year.'</option>';
}
}
echo $_GET['months'];
?>
<input type="submit" value="View Selected Date"></input>
</select>
</form>
My code is very far from complete, or orderly but I have been slacking on this project and I will clean it up more when I have more time. But if you could please give me a hand on an efficient organizational method that would be appreciated.
Do your tables contain an index/id?
You can easily order them in ascending/descending by "ORDER BY"
ALTER TABLE `table_name` ORDER BY `id`
Note default ORDER BY is in ascending order. Put DESC at the end if you want descending.
If you want your mysql query to output results in a nice ordered fashion, you can also use ORDER BY in the query:
$gathermonths = "SELECT `month`, `year` FROM `month` ORDER BY `month` DESC";
There is also GROUP BY functions in case you wanted to group your results by month:
$gathermonths = "SELECT `month`, `year` FROM `month` GROUP BY `month`";
Instead of the DESCRIBE query, you could use mysql_fetch_field. Then columns will always be in the same order you have on your SELECT:
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
// Loop the columns to build the table headers
echo '<table>';
echo '<tr>';
while ($i < mysql_num_fields($query_run)) {
$field = mysql_fetch_field($query_run, $i);
echo '<th>' . $field->name . '</th>';
$i++;
}
echo '</tr>';
// Your current data loop
while($row = mysql_fetch_assoc($query_run)){
// (...)
}
echo '</table>'
}
?>
Since you're already specifying which columns you're fetching, simply output the column headers explicitly rather than querying the database.
Contrariwise, if you want to abstract the HTML table generation code so that it works with arbitrary SQL tables (thus separating data access from display), record the column names as you generate the column headers in an array, then iterate over this array when outputting rows. You can also do away with the $rent = $row['rent']; assignments, as they gain you nothing. Using PDO:
/* data access */
$finances = $db->query('SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month`');
$columns = array();
for ($i = 0; $i < $finances->columnCount(); ++$i) {
$meta = $finances->getColumnMeta($i);
$columns[$meta['name']] = ucwords($meta['name']);
}
/* data display. Note this is completely independent of the type used to store
the colum & row data. All that matters are that $columns and $finances are
Traversable
*/
?>
<table>
<thead>
<tr>
<?php foreach ($columns as $name => $label): ?>
<th><?php echo $label ?></th>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach ($finances as $monthly): ?>
<tr>
<?php foreach ($columns as $name => $label): ?>
<td><?php echo $monthly[$name]; ?></td>
<?php endforeach ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Error handling and abstraction into modules left as an exercise.

PHP SQL events by Month and Year

UPDATED PHP
Seems to be something to do with Angle brackets...
My first time coding my own PHP and SQL, but having a bit of trouble, so not even plugged HTML in yet. I'd imagine I'm not escaping something right, or my formatting is miles off... or something REALLY simple.
I'm basically trying to get a list of events working, and many posts on it here, just can't put them all together to get a result.
So I'm looking for
YEAR
MONTH
EVENT
MONTH
EVENT
EVENT
YEAR etc
My HTML looks like this...
<div id="year">
<p class="vert">YEAR</p>
<div id="month">
<h1>MONTH</h1>
<div class="event">
<p>DATE START - DATEEND IF DIFFERENT/AVAILABLE</p>
<div class="eventmain">
<img class="flag" src="./img/defaultflag.png">
<img class="open" src="./img/plus.png">
<img class="close" src="./img/minus.png">
<h2> Event Name </h2>
<div class="eventdetails">
<p>FORMAT</p>
<p>INFO</p>
<p>CONTACT</p>
<p>EMAIL</p>
<p>WEBSITE</p>
</div> <!-- close div event details -->
</div> <!-- close div event main -->
</div> <!-- close div event -->
</div> <!-- close div month -->
</div> <!--close div year-->
With the following DB fields in the DB debate_calendar, table events
event_name, event_startdate, event_enddate, event_flag, event_format, event_info,event_contactinfo, event_email, event_website, event_reg
I have the following PHP
<?php
$server = "localhost:8889";
$user = "root";
$passwd = "root";
$db_name = "debate_calendar";
$table_name = "events";
$conn = mysql_connect($server, $user, $passwd) or die("Couldn't connect to SQL Server on $server");
mysql_select_db($db_name, $conn);
if (!$conn)
{
exit("Failed to Connect to $dbConnection");
}
else
{
echo "Database Connected";
}
$query = "SELECT * FROM `debate_calendar`.`events` WHERE event_date > NOW() ORDER BY event_date DESC";
$result = mysql_query( $query );
$current_month = '';
$current_year = '';
while ($event = mysql_fetch_assoc($result)) {
$year = date('y', $event['event_startdate']);
if($current_year != $year)
{
$current_year = $year;
echo ("<h1>" .$current_year. "</h1>");
}
$month = date('m', $event['event_startdate']);
if($current_month != $month)
{
$current_month = $month;
echo '<h2>' . $current_month . '</h2>';
}
echo '<p>' . $event['event_name'] . '</p>';
}
mysql_close($con);
?>
But all it's generating is...
NOW() ORDER BY event_date DESC"; $result = mysql_query( $query ); $current_month = ''; $current_year = ''; while ($event = mysql_fetch_assoc($result)) { $year = date('y', $event['event_startdate']); if($current_year != $year) { $current_year = $year; echo ("
" .$current_year. "
"); } $month = date('m', $event['event_startdate']); if($current_month != $month) { $current_month = $month; echo '
' . $current_month . '
'; } echo '
' . $event['event_name'] . '
'; } mysql_close($con); ?>
echo <p> Your Database is Connected</p\><br/\>
You forgot to add the quotes ("")
try this:
echo "<p> Your Database is Connected</p\><br/\>";
You didn't quote your last echo before $qry. Also, there are some extra characters in your query that will make it fail. This is how it should look:
SELECT * FROM `debate_calendar`.`events` WHERE event_date > NOW()
ORDER BY event_date DESC
Also, you can get year/month/date parts of any DATE/DATETIME type field directly from SQL if you want:
SELECT year(event_date) AS event_year, month(event_date) AS event_month ...
The answer was a schoolboy error.
I had moved the site from one MAMP install to a fresh one,
where the htaccess hadn't been changed to allow html files to be opened as PHP.
Still lots of errors in the code, but this was the underlying problem
Simple as that!!

Categories