Query just day month year from now() - php

I am inserting a date into a database with NOW() then I query the result. Here is the code.
function get_content($id = ''){
if($id != ''):
$id = mysql_real_escape_string($id);
$sql = "SELECT * FROM cms_content WHERE id = '$id'";
$return = '<p>Back to Content</p>';
else:
$sql = "SELECT * FROM cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
while($row = mysql_fetch_assoc($res)) {
echo '<h1> ' . $row['title'] . '</h1>';
echo '<p>' . stripslashes($row['body']) . '</p>';
**echo '<p>' . $row['date_posted'] . '</p>';**
}
else:
echo '<p> You broke it!, this post dosn\'t exsist!';
endif;
echo $return;
The
echo '<p>' . $row['date_posted'] . '</p>';
is where I echo the date. When I echo this from the database I get 2012-07-25 19:00:46, because that's what is in the database. My question is how would I echo the day, then echo the month, then the year. Ideally these would all be separate echos so I could style each differently.

This is alot more handy and less code.
$date = new DateTime($row['date_posted']);
$day = date->format('d');
$month = date->format('F');
$year = date->format('Y');
Resource: http://www.php.net/manual/en/class.datetime.php

Since the format is known, you can simply use this:
list($year,$month,$day) = explode("-",substr($row['date_posted'],0,10));
Then you can echo those variables however you want.

$date = strtotime($row['date_posted'];
echo date('d', $date);
echo date('m', $date);
echo date('Y', $date);
or
$date = new DateTime($row['date_posted']);
echo $date->format('Y');
etc

You would use php built in date() function: http://us.php.net/manual/en/function.date.php
echo "<p>".date('j M, Y', $row['date_posted'])."</p>";
// would output <p>25 July, 2012</p>
This can be modified into just about any format that you would like.

Another option is to do that directly in SQL, using the *date_format* function: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Related

Why does time() malfunction after midnight in my MySQL query?

I have two tables that my Query affects. The tables are called flightSched & Alteration. In both tables the arrivalTime column is of type TIME.
The query runs just fine until the $CurrentTimePlus4Hours variable elapses midnight. When this happens, the query doesn't yield any records, although the table has data ranging from all times of the day and night. Find below my code.
$currentDay = date('l');
$CurrentTimeMinus30min = date('H:i:s', strtotime('-30 minutes'));
$CurrentTimePlus4Hours = date('H:i:s', strtotime('+240 minutes'));
$query2 = "SELECT * FROM flightSched WHERE don = '$currentDay'
AND depOrArriv='Arrival'
AND arrivalTime BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours'
ORDER BY arrivalTime ASC ;";
$query2 .= "SELECT * FROM Alteration WHERE don = '$currentDay'
AND depOrArriv='Arrival'
AND arrivalTime BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours'
ORDER BY arrivalTime ASC ;";
/* execute multi query */
if ($mysqli->multi_query($query2)) {
do
{
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_array()) {
echo "<tr " . $variable . "><td>";
echo '<img src="php/displayImage.php?id=' . $row['id'] . ' "align="middle" width="110" height="35" >' . " "
. $row['flightNo'] ;
$flightNo = $row['flightNo'];
echo "</td><td>";
echo $row['airline'];
echo "</td><td>";
echo $row['origin'];
echo "</td><td>";
echo $row['arrivalTime'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
if ($variable == 'id=basicBoard')
{
$variable = 'class=alt';
//echo $variable;
}
elseif ($variable == 'class=alt')
{
$variable = 'id=basicBoard';
//echo $variable;
}
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
// printf("-----------------</br>");
}
}
while (#$mysqli->next_result());
echo "</table> <br/> <br/>";
}
I have tried to figure out why this happens but failed to fix the issue. Can someone kindly point out where I am going wrong in the code?
I think you just need to compensate for the time lapse by offsetting what the "current" day is:
$midnight = strtotime('today');
$now = time();
$tomorrow = $midnight + 86400;
$diff = $tomorrow - $now;
$offset = $now;
// Number of seconds in 240 minutes = 14400
if ($diff <= 14400) {
$offset += $diff;
}
$currentDay = date('l', $offset);
$CurrentTimeMinus30min = date('H:i:s', strtotime('-30 minutes'));
$CurrentTimePlus4Hours = date('H:i:s', strtotime('+240 minutes'));

SQL Syntax Error via php

I'm kinda new to php, this place has been a great help for me so far! Anyway, I have this code
$month = "
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "
";
That's what I get when I echo out $month
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '1070757'
AND MONTH(atc_online) = 07
AND YEAR(atc_online) = 13
When i use this directly into phpMyAdmin, works as a charm, but when I try to do it through a php webpage, I get the syntax error. I'm using php 5.4
Thanks!
Edit: Full Code:
<?php
//open MySQL connection
$mysql = mysqli_connect('host', 'un', 'pass', 'table')
or die ( "MySQL Error: ".mysqli_error() );
//Get and decode residents data
$jsonData = file_get_contents("link");
$phpArray = json_decode($jsonData, true);
//Start Operations
foreach ($phpArray as $key => $value) {
//Get controller hours for today
$vatsimid = $value[vatsimid];
//Get previous month
$pmonth = date("m", strtotime("-35 days") ) ;
$pmonthName = date("M", strtotime("-35 days") ) ;
echo $pmonth;
echo $pmonthName;
//This year or last year?
If (date("M") != "Jan") { //Checks that it's not January of the next year.
$year = date("y");
}
else {
$year = date("y", strtotime("-1 month") );
}
echo $year;
//Search and sum entries during last month
$month = "SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "";
echo $month;
echo "</br> </br>";
$result = mysqli_query($mysql,$month);
$row = mysqli_fetch_assoc($result);
$month_sum = $row['month_sum'];
echo $month_sum;
//Updates data in atclist
$datainsert = "
UPDATE `atclist`
SET " . $monthName . "=" . $month_sum . "
WHERE vatsimid = " . $vatsimid . "";
$insert = mysqli_query($mysql,$datainsert);
if (!$insert)
{
die('Error: ' . mysqli_error($mysql));
}
}
/*
Did you mean:
SELECT SUM(duration) AS month_sum
FROM connlist
WHERE vatsimid = '1070757' AND MONTH(atc_online) = 07 AND YEAR(atc_online) = 13
It looks like $month_sum variable is not set or empty in your UPDATE query.
You can add single quotes like
$datainsert = "
UPDATE atclist
SET ".$monthName."= '".$month_sum."'
WHERE vatsimid= '".$vatsimid."'";

How can I use to two MySQLi queries in separate for each statements?

I'm trying to use a row from a MySQLi result within a secondary query.
but im getting some unexpected results.
<?php
$mysqli = new mysqli('connection');
if ($mysqli->connect_error) {die('Connect Error: ' . $mysqli->connect_error);}
$today = date("Ymd");
$query = "SELECT course FROM dailytips WHERE date = 20130724 GROUP BY course";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
$rows[] = $row; }
foreach($rows as $row)
{
echo $row['course'] . "<br/>";
$query2 = "SELECT horse, time, date FROM dailytips WHERE date = 20130724 and course ='{$row['course']}' ORDER BY time";
$result2 = $mysqli->query($query2);
$today_uk = " " . date("d/m/y");
while($row2 = $result2->fetch_array())
{
$rows2[] = $row2;
}
foreach($rows2 as $row2)
{
$date = $row2['date'];
$date = date("d/m/y", strtotime($date));
echo '<div style= "width:600px; font-family:verdana;"><div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">'.$row2['time'] . "-" . $row2['horse'] .' </div>' ;
}
}
$result->close();
$mysqli->close();
?>
my page currently looks like -
ipswich
11:00-running
12:00-flamingo rider
14:00-lightning
norwich
11:00-running
12:00-flamingo rider
14:00-lightning
13:10-ed is back
14:05-redrum
17:05-pickle
whereas I want
ipswich
11:00-running
12:00-flamingo rider
14:00-lightning
norwich
13:10-ed is back
14:05-redrum
17:05-pickle
to be returned.
How can I free the result in the second for each query?
Good heavens what a mess.
Try this.
<?php
$mysqli = new mysqli('connection');
if ($mysqli->connect_error) {die('Connect Error: ' . $mysqli->connect_error);}
$today = date("Ymd");
$query = "SELECT course FROM dailytips WHERE date = 20130724 GROUP BY course";
$result = $mysqli->query($query);
$row = $result->fetch_array();
echo $row['course'] . "<br/>";
do {
$query2 = "SELECT horse, time, date FROM dailytips WHERE date = 20130724 and course ='{$row['course']}' ORDER BY time";
$result2 = $mysqli->query($query2);
$today_uk = " " . date("d/m/y");
while($row2 = $result2->fetch_array())
{
$date = $row2['date'];
$date = date("d/m/y", strtotime($date));
echo '<div style= "width:600px;font-family:verdana;"><div style="float:left; width:400px; margin-bottom:10px; margin-top:10px;">'.$row2['time'] . "-" . $row2['horse'] .' </div>' ;
}
} while ( $row = $result->fetch_array() );
$result->close();
$result2->close();
$mysqli->close();
?>

How can I categorise MySQLi result set?

How can I change the code below so that I am only echoing each unique '$course' only once?
eg. currently my results look like =
ipswich-11:00-running
ipswich-12:00-flamingo rider
ipswich-14:00-lightning
norwich-13:10-ed is back
norwich-14:05-redrum
norwich-17:05-pickle
but I would like them to look like =
Ipswich
11:00-running
12:00-flamingo rider
14:00-lightning
norwich
13:10-ed is back
14:05-redrum
17:05-pickle
I thought about doing a mysqli query in a for each loop, but surely there is a better way?
My code =
<?php //connection block
if ($mysqli->connect_error) {die('Connect Error: ' . $mysqli->connect_error);}
$today = date("Ymd");
$query = "SELECT horse, course, time, date FROM dailytips WHERE date = $today ORDER BY course, time";
$result = $mysqli->query($query);
$today_uk = " " . date("d/m/y");
while($row = $result->fetch_array())
{ $rows[] = $row; }
echo "<h2>tips for" .$today_uk. "</h2>";
foreach($rows as $row)
{
$date = $row['date'];
$date = date("d/m/y", strtotime($date));
$horse = $row['horse'];
$time = $row['time'];
$course = $row['course'];
echo
'<div style= "width:600px; font-family:verdana;">
<div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">
'.$row['course']. "-" .$row['time'] . "-" . $row['horse'] .'
</div>' ;
}
$result->close();
$mysqli->close();
?>
I guess you could nest a foreeach statement inside another.
so...
$query = "SELECT course, FROM dailytips WHERE date = $today ORDER BY course, time";
while($row = $result->fetch_array())
{ $rows[] = $row; }
echo "<h2>tips for" .$today_uk. "</h2>";
foreach($rows as $row) {
$query = "SELECT horse, time, date FROM dailytips WHERE course = $row['course'];
while($row = $result->fetch_array())
{ $rowDetail[] = $rowDetails; }
foreach($rows as $row) {
$date = $row['date'];
$date = date("d/m/y", strtotime($date));
$horse = $row['horse'];
$time = $row['time'];
$course = $row['course'];
echo
'<div style= "width:600px; font-family:verdana;">
<div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">
'.$row['course']. "-" .$row['time'] . "-" . $row['horse'] .'
</div>' ;
}
}
I would consider putting your results in a table opposed to DIVs as this would seem to fit what you are trying to do much better. Set the table up before the loop and close once the loop has been exited.

PHP: Compare Date

I'm encountering the following problem:
I'd like to compare today's date against some dates in a database, then if it isn't expired yet, show something... but if all the dates in the table are expired, show something like 'No lecture scheduled at this time, return again'.
As for the first thing it's no problem, but I can't show the text where there aren't any future dates...
Here's the code,
Table:
id, dateposted, date_course, title, body
$sql = "SELECT *
FROM L
ORDER BY L.dateposted DESC;";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$exp_date = $row['date_course'];
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date >= $today)
{
echo "<a href='courses.php'>" . $row['title']. "</a>";
echo "</br>";
}
}
I'll assume you're using MySQL. A couple of small changes to your query and code should make this work. You should definitely do this kind of filtering in the query and not the code.
$sql = "SELECT *
FROM L
WHERE date_course < NOW() AND dateposted < NOW()
ORDER BY L.dateposted DESC;";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
echo "<a href='courses.php'>" . $row['title']. "</a>";
echo "</br>";
}
}
else
{
echo "No results available";
}
Several ways to do it. One would be to make the date comparison part of the query. If no rows are selected, show your special message.
Otherwise, you can set a flag like
$has_courses = false;
while ($row = fetch() {
$has_courses = true;
...
}
if (!$has_courses) { echo 'No courses'; }
Although you could do this far more efficiently by improving your query, here is the specific fix you request:
$sql = "SELECT *
FROM L
ORDER BY L.dateposted DESC;";
$result = mysql_query($sql) or die(mysql_error());
$out = false;
while($row = mysql_fetch_assoc($result))
{
$exp_date = $row['date_course'];
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date >= $today)
{
$out = true;
echo "<a href='courses.php'>" . $row['title']. "</a>";
echo "</br>";
}
}
if (!$out)
echo 'Nothing found.';

Categories