How can I categorise MySQLi result set? - php

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.

Related

php return stops the loop

good day I write a function where I want to display the records which will match on the dates last week but it only loop one time. Is there a way to return all the dates and show all the records that will match with the dates? Here is my code.
function fetch_week(){
$today = date('F d Y');
for($i = 1; $i <= 7; $i++)
{
$repeat = strtotime("-1 day",strtotime($today));
$today = date('F d Y',$repeat);
$output = '';
$conn = mysqli_connect("localhost", "root", "", "sample");
$sql = "SELECT * FROM list WHERE datee = '".$today."' ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if(empty(mysqli_num_rows($result))){
echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
}
else{
while($row = mysqli_fetch_assoc($result)){
$output .= '<tbody id="appTable">
<tr class="content" style="font-weight: normal text-align: center">
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["contact"].'</td>
<td>'.$row["datee"].'</td>
</tr>
</tbody>
';
}
return $output;
}
}
}
You can create an array and return that after your loop ends. Check below code:
function fetch_week() {
$today = date('F d Y');
$response = [];
for ($i = 1; $i <= 7; $i++) {
$repeat = strtotime("-1 day", strtotime($today));
$today = date('F d Y', $repeat);
$output = '';
$conn = mysqli_connect("localhost", "root", "", "sample");
$sql = "SELECT * FROM list WHERE datee = '" . $today . "' ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (empty(mysqli_num_rows($result))) {
echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
} else {
$output = '<tbody id="appTable">';
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tr class="content" style="font-weight: normal text-align: center">
<td>' . $row["name"] . '</td>
<td>' . $row["address"] . '</td>
<td>' . $row["contact"] . '</td>
<td>' . $row["datee"] . '</td>
</tr>';
}
$output .= '</tbody>';
$response[] = $output;
}
}
return $response;
}
You need to loop through on output to print your data. But apart from all these, your code is widely open for SQL injection. Please be careful and do changes for that. Also you don't need to create tbody again and again in loop. You can do that first time only which I have changed in above code as well.
Hope it helps you.

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.

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

Populating a DropDown from SQL database in PHP

I'm attempting to get data from a SQL database in order to populate a couple drop downs. This is an excerpt, but I can post more if you'd like. I didn't include it all because its more than a couple lines.
$queryData = mysql_query("SELECT DISTINCT DateTime AS DateTime FROM 'historicaldata' ORDER BY YEAR(DateTime), DAYOFYEAR(DateTime)");
$queryGroups = mysql_query("SELECT DISTINCT histgroupname AS GroupName FROM 'historicalgroups' WHERE `histgroupID` < 10 ORDER BY `histgroupname`");
$tracker = 0;
$dataArray = array();
$groupsArray = array();
$DateFormat1 = array();
$DateFormat2 = array();
$DayNumber = array();
$Month = array();
$Year = array();
while ($row = mysql_fetch_array($queryData)) {
$dataArray[$tracker] = $row['DateTime'];
$tracker++;
}
$tracker = 0;
while ($row = mysql_fetch_array($queryGroups)) {
$groupsArray[$tracker] = $row['GroupName'];
$tracker++;
}
$tracker = 0;
foreach ($dataArray as $l) {
$p = strtotime($l);
$x = getdate($p);
$DateFormat1[$tracker] = date("D M d, Y", $x);
$DateFormat2[$tracker] = date("M Y", $x);
$DayNumber[$tracker] = date("z", $x);
$Month[$tracker] = date("n", $x);
$Year[$tracker] = date("Y", $x);
$tracker++;
}
echo "<div id='Period1'> <span class='regblue'>Start</span><select name='startdate'><option value=''></option>";
foreach($DateFormat1 as $x)
echo "<option selected value='$x'>$x</option>";
echo "</select> </div>";
For some reason, the drop down remains empty no matter what I try.
Why are you using such a complex code. Use the power of php of integrating itself with HTML.
Try this Style.
And check if you have established a connection with the database or not.
<?php
require_once('connection.php'); //establish the connection with the database on this page.
$queryData = mysql_query("SELECT DISTINCT DateTime AS DateTime FROM 'historicaldata' ORDER BY YEAR(DateTime), DAYOFYEAR(DateTime)");
$queryGroups = mysql_query("SELECT DISTINCT histgroupname AS GroupName FROM 'historicalgroups' WHERE `histgroupID` < 10 ORDER BY `histgroupname`");
$result = mysql_fetch_array(mysql_query($queryData)); //$result now has database tables
$resultGroups = mysql_fetch_array(mysql_query($qrueryGroups)); //$resultGroups has now database tables
?>
<select name='Date'>
<?php
while($row = mysql_fetch_array($result))
{
?>
<option values=<?php echo($row['DateTime']); ?><?php echo($row['DateTime']); ?></option>
<?php
}
?>
</select>
<?php
?>
You may try like this
<?php
require_once('db_connect.php'); //connect with the database.
$queryData = mysql_query("SELECT DISTINCT DateTime AS DateTime FROM 'historicaldata' ORDER BY YEAR(DateTime), DAYOFYEAR(DateTime)");
$queryGroups = mysql_query("SELECT DISTINCT histgroupname AS GroupName FROM 'historicalgroups' WHERE `histgroupID` < 10 ORDER BY `histgroupname`");
$result = mysql_fetch_array(mysql_query($queryData)); //$result now has database tables
$resultGroups = mysql_fetch_array(mysql_query($qrueryGroups)); //$resultGroups has now database tables
echo '<select name="Date" id="Date">';
while($row = mysql_fetch_assoc($result))
{
echo '<option values=' . $row["DateTime"] . '>' . $row["DateTime"] . '</option>';
}
echo '</select>';
?>

Categories