Date function not working with bind_result - php

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.

Related

Object of class PDOStatement could not be converted to string - get dropdown list to dynamical display data

I'm pretty new to PHP and I'm stuck on on this last bit of code. its coming up with the below error and I'm not sure how to fix it.
Object of class PDOStatement could not be converted to string in
/home/e0753906/public_html/test4.php on line 70
I'm try to get the data in my database to display in a table once the selected date have been chosen from the dropdown list. the Date chosen in the dropdown list need to be the date in the WHERE clause.
my php file looks like this:
<?php
// set up database global variables
$servername = "localhost";
$username = "e0753906_Sam";
$password = "Tamara1623";
//connect to the database
try {
$conn = new PDO("mysql:host=" . $GLOBALS['servername'] .
";dbname=e0753906_OaktownFootball", $GLOBALS['username'],
$GLOBALS['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "An error occured: " . $e->getMessage();
}
// global variables
$query = $conn->query('SELECT DISTINCT `Date` FROM Fixtures');
$data = $conn->query('SELECT * FROM Fixtures');
$test = $conn->query('SELECT * FROM Fixtures WHERE `Date`=20160709');
$data_s = $conn->query('SELECT Date,
(SELECT Team_Name FROM Teams WHERE Teams.Team_ID =
Home_team.Team_ID) As Home_Team,
(SELECT Team_Name FROM Teams WHERE Teams.Team_ID =
Away_team.Team_ID) As Away_Team,
Home_Score,
Away_Score
FROM Fixtures
JOIN Home_team ON Home_team.Home_Team_ID =
Fixtures.Home_Team_ID
JOIN Away_team ON Away_team.Away_Team_ID =
Fixtures.Away_Team_ID');
?>
<html>
<head>
<title>Oaktown Football Club</title>
</head>
<body>
<form action="test2.php" method="get">
<select name="Date">
<option>Choose a date</option>
<?php foreach ($query->fetchAll() as $Fixtures):?>
<option name="Date" value="<?php echo $Fixtures['Date'];?>">
<?php echo $Fixtures['Date'];?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Show details">
</form>
<?php
echo "<table border=1>
<tr>
<th>Date</th>
<th>Home Team</th>
<th>Away Team</th>
<th>Score</th>
</tr>" ;
if (isset($_GET['Date'])) {
ob_start();
echo $_GET['Date'];
$datetest = ob_get_contents();
$fixture = "
{$data_s}
WHERE `Date` = ' . $datatest . '";
while($records = $fixture->fetch()) {
echo "<tr>";
echo "<td>" . $records['Date'] . "</td>";
echo "<td>" . $records['Home_Team'] . "</td>";
echo "<td>" . $records['Away_Team'] . "</td>";
echo "<td>" . $records['Home_Score'] . "-" .
$records['Away_Score'] . "</td>";
echo "</tr>";}
}
echo "</table>" ?>
</body>
Thanks
I have also tried
//Get data from date
if (isset($_GET['Date'])) {
$dateQuery = "
{$data}
WHERE `Date` = :date";
$date = $conn->prepare($dateQuery);
$date->execute(['date'=>$_GET['Date']]);
$selectedDate = $date->fetch(POD::FETCH_ASSOC);
var_dump($selectedDate);};
When you set $data_s, this is the result of executing a query, so in the line..
$fixture = "
{$data_s}
WHERE `Date` = ' . $datatest . '";
Your trying to add the result of executing the query into the string. As I think your just trying to add the WHERE clause onto the end of this statement, I think you can just need to set $data_s to...
$data_s = 'SELECT Date,
(SELECT Team_Name FROM Teams WHERE Teams.Team_ID =
Home_team.Team_ID) As Home_Team,
(SELECT Team_Name FROM Teams WHERE Teams.Team_ID =
Away_team.Team_ID) As Away_Team,
Home_Score,
Away_Score
FROM Fixtures
JOIN Home_team ON Home_team.Home_Team_ID =
Fixtures.Home_Team_ID
JOIN Away_team ON Away_team.Away_Team_ID =
Fixtures.Away_Team_ID';
But I'm also not sure about ...
ob_start();
echo $_GET['Date'];
$datetest = ob_get_contents();
You could remove this and just use ...
$fixture = "
{$data_s}
WHERE `Date` = ' . $_GET['Date'] . '";
Update:
As this now doesn't execute the query, you need to do it here...
$fixture = $conn->query("{$data_s}
WHERE `Date` = '".$_GET['Date']}."'");
if ( $fixture === false ) {
die ($conn->error);
}

Invalid argument supplied for foreach()

i'm coding a project and have some troubles when the system inform error:
Invalid argument supplied for foreach() in:
foreach($dbh->query($q1) as $row)
and can't get data from the database. How can i fix it, im a newbie, so if i don't understand, please teach me! thanks!
thank for your helps but i still can't fix it
<?php include("top.html"); ?>
<body>
<div id="main">
<h1>Results for <?php echo $_GET['firstname'] . " " . $_GET['lastname'] ?></h1> <br/><br/>
<div id="text">All Films</div><br/>
<table border="1">
<tr>
<td class="index">#</td>
<td class="title">Title</td>
<td class="year">Year</td>
</tr>
<?php
$dbh = new PDO('mysql:host=localhost;dbname=imdb_small', 'root', '');
$q1 = "SELECT id
FROM actors
WHERE first_name = '".$_GET['firstname']."' AND last_name = '".$_GET['lastname']."'
AND film_count >= all(SELECT film_count
FROM actors
WHERE (first_name LIKE'".$_GET['firstname']." %' OR first_name = '".$_GET['firstname']."')
AND last_name = '".$_GET['lastname']."')";
$id = null;
foreach($dbh->query($q1) as $row){
$id = $row['id'] ;
}
if($id == null){
echo "Actor ".$_GET['firstname']." ".$_GET['lastname']."not found.";
}
`
$sql2 = "SELECT m.name, m.year
FROM movies m
JOIN roles r ON r.movie_id = m.id
JOIN actors a ON r.actor_id = a.id
WHERE (r.actor_id='".$id."')
ORDER BY m.year DESC, m.name ASC";
$i = 0;
foreach($dbh->query($sql2) as $row){
echo "<tr><td class=\"index\">";
echo $i+1;
echo "</td><td class=\"title\">";
echo $row['name'];
echo "</td><td class=\"year\">";
echo $row['year'];
echo "</td></tr>";
$i++;
}
$dbh = null;
?>
</table>
</div>
</div>
<?php include("bottom.html"); ?>
</body>
</html>
Check that your query succeeded before iterating on the result:
if (false !== ($result = $dbh->query($d1))) {
foreach($result as $row){
$id = $row['id'] ;
}
}
By the way, I don't understand what you are trying to do with this pointless loop.
You could do this
$st = $dbh->query($q1);
if ( $st ) {
while ( $row = $st->fetch() ) {}
}
Try to make your code more readable
$result = $dbh->query($q1);
foreach($result as $row){$id = $row['id'];}

SQL Query only displaying first result rather than arrayed data

Basically I am building a calendar page that displays the months, and the days of the month(pulled from my database) and then any days that are inside the "start_date - end_date" variables are displayed with a different cell background color to the days that don't have a start or end date assigned, I have it working to an extent but it's only displaying the earliest of each months record rather than all the results.
ie.
2015-03-12(start) - 2015-03-16(end)
2015-03-03(start) - 2015-03-10(end)
And rather than display like this...
`1 2 [3 4 5 6 7 8 9 10] 11 [12 13 14 15 16] 17 18 19 20 ...`
it's just showing the [3 - 10] record, here is my current code..
<table width="100%" cellspacing="0">
<?php
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = mysql_fetch_assoc($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
Also I am aware of the dangers not using mysqli but I am just learning this on my local machine and plan on researching updated strategies once I get the functions working, so I'll know if my functions are broken or my coding is.
Thanks
try with common function to read data from table
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = db_set_recordset($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
You are only fetching one row of your result set from your trips table. You need something like this to get the second one.
while ( $row = mysql_fetch_assoc($res2) ) {
/* process each row */
}
You're doing this right for your other result set. Take a look at the examples here: http://php.net/manual/en/function.mysql-fetch-assoc.php
You'll need to run through the result set rows and accumulate your "hot" days, then render the days just once. Something like this:
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
while ($row = mysql_fetch_assoc($res2)) {
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
$hot_days = array();
foreach(range(1, $month_end) as $days) {
$hot_days[$days] = 0;
if(in_array($days, range($start, $end))) {
$hot_days[$days] ++;
}
}
}
/* now you have a $hot_days array with nonzero values for interesting days */
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $day) {
if($hot_days[$day] > 0) {
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else {
echo "<td align=\"center\">" . $days . "</td>";
}
}
?>
</tr>
With respect, I don't have time to debug this.

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.

Categories