get datetime from a sql database - php

Im trying to get the datetime to get a form of date.
<?php
$con = mysql_connect("******","******","*****");
if($con) {
$db = mysql_select_db("*****");
if($db) {
$sql = "SELECT title, longstory, author, published FROM cms_news ORDER BY id DESC LIMIT 3";
$result = mysql_query($sql);
if($result) {
while($row = mysql_fetch_array($result)) {
echo "<ul class='menu-list' id='news-list'>";
echo "<li><a href='{url}/news/".$row['id']."'>".$row['title']."<span>".$row['published']."</span></a> </li>";
echo "</ul>";
}
echo "</table>";
} else
echo "";
} else
echo "";
} else
echo "";
?>
http://prntscr.com/eedv2w
That inside the red is the code. But i wants it like that under.

You can use as below:
Instead of $row['published'] You can use date('l d. F Y', strtotime($row['published']))
If you store direct strtotime into the database then you need to replace with date('l d. F Y', $row['published'])

Related

While nested lops in php fetching data from sql database

$sql = "SELECT * FROM today WHERE heading='$heading' and day='$day'";
$sql1 = "SELECT * FROM today WHERE day='$day'";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result->num_rows > 0) {
echo "<div id='post'><h1>".$row["heading"]."</h1>
<aside class='related-post'>".while($row = $result1->fetch_assoc())
{echo'<img src='".$row["image"]."'>;}
.</aside>}";
I have been using while loops for fetching data from table. My connection is working is perfect but I need another loop in the first that is not working. Isn't it the good way?
Update: I tried to finish echo and again started as follow but still an error
while($row = $result->fetch_assoc()) {
echo "<div id='post'><h1>"
.$row["heading"].
"</h1><div class='post-side'><img class='post-image' src='"
.$row["image"].
"'><div class='post-data'><p><strong>Age: </strong><span>$age</span></p><p><strong>Date of birth: </strong><span>"
.$row["day"].
"-"
.$row["month"].
"-"
.$row["year"].
"</span></p></div></div></div><div class='description'><p>"
.$row["description"].
"</p></div><div class='bottom-related'><aside class='related-post'>";
while($row = $result1->fetch_assoc())
{echo"<img src='"
.$row["image"].
"'>/";}.echo"</aside><aside class='ad2'>".$includead."</aside></div>";
}
echo "</div>";
} else {
echo "No table found";
}
$conn->close();
You're trying to concatenate to a string a WHILE loop; this is wrong.
You should echo your first part, end with it and then do your while loop, and echo the end afterwards:
Your quotes are a bit messed up as well
if ($result->num_rows > 0)
{
echo "<div id='post'><h1>".$row["heading"]."</h1>
<aside class='related-post'>";
while($row = $result1->fetch_assoc())
{
echo'<img src="'.$row["image"].'">';
}
echo '</aside>';
}
You can't concatene while with String, it's a syntaxic error
Also, you have a probleme when trying to echo a String, you can use this syntax:
echo "PHP"; // will evaluate PHP variables and whitespace inside a string
echo 'PHP'; // will evaluate nothing;
But you can not start flushing a string ' and finish by " or vice-versa.
Here the correct code :
<?php
$sql = "SELECT * FROM today WHERE heading='$heading' and day='$day'";
$sql1 = "SELECT * FROM today WHERE day='$day'";
$result = $conn->query($sql);
$result1 = $conn->query($sql1);
if ($result->num_rows > 0) {
echo "<div id='post'><h1>" . $row["heading"] . "</h1><aside class='related-post'>";
while($row = $result1->fetch_assoc()) {
echo'<img src="' . $row["image"] .'">';
}
echo "</aside>";
}

Date function not working with bind_result

I have this date format in place in my files. It works great if I do a normal SELECT query, but when I do a prepared statement query that does not have a bind_param and assign it a bind_result variable, I cannot get this to work.
Here is the function. Which it displays in US Central time. How can I get that to Eastern time?
function fixDate($strDateTime) {
$strFormat = 'M, j, Y';
$strFormatTime = '\a\t g:ia';
$intTimeStamp = strtotime($strDateTime);
$strDate = date($strFormat, $intTimeStamp);
$strTime = date($strFormatTime, $intTimeStamp);
if($strDate == date($strFormat)) {
return "Today " . $strTime;
}
elseif($strDate == date($strFormat, strtotime('yesterday'))) {
return "Yesterday " . $strTime;
}
else {
return " on " . $strDate . " " . $strTime;
}
}
The function will work if I do this with a normal SELECT query.
$date = $row2['topic_date'];
$date = fixDate($date);
BUT if I have a bind_result of $date and try to do this
$date = fixDate($date);
It won't work.
How can I get this function to work with a prepared statement's bind_result variable?
UPDATE:
This works..
$query2 = mysqli_query($con,"SELECT * FROM forum_topics
INNER JOIN forum_categories ON
forum_topics.category_id = forum_categories.id
INNER JOIN users
ON forum_topics.topic_creator = users.id
ORDER BY forum_topics.topic_reply_date DESC
LIMIT 3")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
if($numrows2 > 0){
$topics .= "<table class='top_posts_table'>";
$topics .= "<tr><th class='top_posts_th'>Topic Title</th><th class='top_posts_th'>Replies</th><th class='top_posts_th'>Views</th></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row2 = mysqli_fetch_assoc($query2)){
$cid = $row2['cid'];
$tid = $row2['id'];
$title = $row2['topic_title'];
$views = $row2['topic_views'];
$replies = $row['tid2'];
$date = $row2['topic_date'];
$date = fixDate($date);
$creator = $row2['username'];
$topics .= "<tr><td class='top_posts_td'><a href='forum_view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator."<br>".$date."</span></td><td class='top_posts_td'>0</td><td class='top_posts_td'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
This doesn't work...
if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.message, announcements.date, users.username FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
}
$announcements_stmt->store_result();
$announcements_result = array();
$announcements_date = $announcements_date;
$announcements_date = fixDate($announcements_date);
?>
<div class="index_announcements_out">
<div id="announcements_title">League Announcements:</div>
<div class="index_announcements_wrap">
<table class="index_announcements_table">
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr class="index_announcements_border">
<td class="index_announcement_pic"></td>
<td class="index_announcement_username_td">FROM: <?php echo $announcements_username; ?><br>on <?php echo $announcements_date; ?></td>
<td class="index_announcement_message_td"><?php echo $announcements_messages; ?></td>
</tr>
Basically, when using bind_result(), you need to do a fetch() before the variables get populated. In this case, you're trying to access them before that happens.
In the given code, it's not necessary to get the fixed $announcements_date outside the while loop, so just replacing <?php echo $announcements_date; ?> with <?php echo fixDate($announcements_date); ?> in the loop should do the trick.

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();
?>

Query just day month year from now()

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

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