Having Trouble Outputting Data correctly From SQL Table - php

I am trying to outputting data from a SQL table
Table cols are:
sheduleID, userID, empID, timeSlot, WeekSlot, daySlot
Connecting to DB
$schedQ = "SELECT * FROM seo_schedule WHERE empID=1 AND weekSlot=1";
$Em1Wk1Res = mysql_query($schedQ) or die(mysql_error());
Displaying Data
echo "<div class='week1'>";
while ($Em1WkRow = mysql_fetch_array($Em1Wk1Res)) {
$clientQ = "SELECT * FROM clients WHERE userID=".$Em1WkRow["userID"]."";
$clientRes = mysql_query($clientQ) or die(mysql_error());
$clientRow = mysql_fetch_array($clientRes);
echo "<div class='day".$Em1WkRow["daySlot"]."'>";
if ($Em1WkRow["timeSlot"] == "am") {
echo "<span class='".$Em1WkRow["timeSlot"]."'>";
echo $clientRow["company"];
echo "</span>";
}
else if ($Em1WkRow["timeSlot"] == "pm") {
echo "<span class='".$Em1WkRow["timeSlot"]."'>";
echo $clientRow["company"];
echo "</span>";
}
echo "</div>";
}
echo "</div>";
Current Output
<div class="week1">
<div class="day1">
<span class="am">Company 1</span>
</div>
<div class="day1">
<span class="pm">Company 1</span>
</div>
<div class="day2">
<span class="am">Company 2</span>
</div>
<div class="day2">
<span class="pm">Company 2</span>
</div>
...etc fir rest of days in week 1
</div>
What I want to be displayed is:
<div class="week1">
<div class="day1">
<span class="am">Company 1</span>
<span class="pm">Company 1</span>
</div>
<div class="day2">
<span class="am">Company 2</span>
<span class="pm">Company 2</span>
</div>
...etc fir rest of days in week 1
</div>
How do I go about doing this....?

You need a nested while to go through the days of the week rendering <span />s inside the week container. I'm not a php dev so can't help you with the implementation, sorry.

The question is do these events depend on a specific time or are you just trying to throw them in 1 company event per day AM and PM? In which case, you can just do:
$arr = array(0 => "am", 1 => "pm");
echo "<div class='week1'>";
while($Em1WkRow = mysql_fetch_array($Em1Wk1Res))
{
$clientQ = "SELECT * FROM clients WHERE userID='" . $Em1WkRow["userID"] . "'";
$clientRes = mysql_query($clientQ) or die(mysql_error());
$i = 0;
$out .= "<div class='day" . $Em1WkRow["daySlot"] . "'>"; // start day
while($clientRow = mysql_fetch_array($clientRes) && $i < 2)
{
// add current day's event
$out .= "<span class='" . $arr[$i++] . "'>";
$out .= $clientRow["company"];
$out .= "</span";
}
$out .= "</div>" // end day
}
echo $out; // display all week's info
echo "</div>"; // end week

This is what I ended up doing...
function emp_schedule($empID) {
$weeks = array(1, 2, 3, 4);
foreach ($weeks as $i => $week) {
$schedQ = "SELECT * FROM seo_schedule WHERE empID=$empID AND weekSlot=$week";
$Em1WkRes = mysql_query($schedQ) or die(mysql_error());
echo "<div class='week'>";
echo "<div class='head'><span class='ts'>Wk ".$week."</span> <span>Monday</span> <span>Tuesday</span> <span>Wednesday</span> <span>Thursday</span> <span>Friday</span></div>";
echo "<div class='ts'><span><strong>AM</strong></span><span><strong>PM</strong></span></div>";
while ($Em1WkRow = mysql_fetch_array($Em1WkRes)) {
$clientQ = "SELECT * FROM clients WHERE userID='".$Em1WkRow["userID"]."'";
$clientRes = mysql_query($clientQ) or die(mysql_error());
while($clientRow = mysql_fetch_array($clientRes)) {
$schd = "<div class='".$Em1WkRow["timeSlot"]."'>";
$schd .= "<span class='client'>".$clientRow["company"]."</span>";
$schd .= "</div>";
$days = array(1, 2, 3, 4, 5);
foreach ($days as $i => $day) {
if ($Em1WkRow["daySlot"] == $day && $Em1WkRow["timeSlot"] == "am" ) {
echo "<div class='day ".$Em1WkRow["daySlot"]."'>";
echo $schd;
}
if ($Em1WkRow["daySlot"] == $day && $Em1WkRow["timeSlot"] == "pm" ) {
echo $schd;
echo "</div>";
}
}
}
}
echo "</div>";
}
}
Mess I Know but it works.

Related

Filter Search Results from a Dropdown in PHP

I have built a search (https://brawlins.com/oer/index.php) and I want to enable user to be able to select filters to limit the search results after their initial search. I have the filters populated in a dropdown menu on my search page (https://brawlins.com/oer/search.php?term=) but I am not sure how to filter down the results once a user clicks on them. I want the users to be able to select multiple options as well. I create a class to store the filters. Below is the code from my filter class:
<?php
class filterContentProvider {
private $conn;
public function __construct($conn) {
$this->conn = $conn;
}
public function getType ($conn) {
$query = $this->conn->prepare("SELECT type, COUNT(*) as total FROM oer_search GROUP BY type");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Type</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Type</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
//$filterHTML .= "<option value=''>- Type -</option>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$type = $row["type"];
$total = number_format($row["total"]);
$filterHTML .= "<a class='dropdown-item' href='search.php?type=$type'>$type ($total)</a>";
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getSubject ($conn) {
$query = $this->conn->prepare("SELECT subject, COUNT(*) as total FROM oer_search GROUP BY subject");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Subject</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Subject</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$subject = $row["subject"];
$total = number_format($row["total"]);
if ($subject != "") {
$filterHTML .= "<a class='dropdown-item' href='search.php?subject=$subject'>$subject ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getLicense ($conn) {
$query = $this->conn->prepare("SELECT license, COUNT(*) as total FROM oer_search GROUP BY license");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>License</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - License</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$license = $row["license"];
$total = number_format($row["total"]);
if ($license != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?license=$license'>$license ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getReviewed ($conn) {
$query = $this->conn->prepare("SELECT review, COUNT(*) as total FROM oer_search GROUP BY review");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Reviewed</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Reviewed</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$review = $row["review"];
$total = number_format($row["total"]);
if ($review != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?review=$review'>$review ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getOrigin ($conn) {
$query = $this->conn->prepare("SELECT source, COUNT(*) as total FROM oer_search GROUP BY source");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Source</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Source</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$source = $row["source"];
$total = number_format($row["total"]);
if ($source != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?source=$source'>$source ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
}
?>
Here is the code I am using on my search.php page. Any help would be much appreciated.
<?php
include("config.php");
include("classes/siteResultsProvider.php");
include("classes/imageResultsProvider.php");
include("classes/filterContentProvider.php");
include("classes/filterImageProvider.php");
if(isset($_GET["term"])){
$term = $_GET["term"];
}
if(isset($_GET["collection"])){
$collection = $_GET["collection"];
}
else {
$collection = "open_content";
}
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>SOAR</title>
<?php
include("header.php");
?>
<div class="wrapper">
<div class="header">
<div class="headerContent">
<div class="searchContainer">
<form action="search.php" method="GET">
<div class="searchBarContainer">
<input type="hidden" name="collection" value="<?php echo $collection; ?>">
<input class="searchBox" type="text" name="term" value="<?php echo htmlspecialchars($term, ENT_QUOTES) ?>" aria-label="search box">
<button class="searchButton">
<img src="images/search-icon.png" alt="search icon">
</button>
</div>
</form>
</div>
</div><!--end of headerContent-->
<div class="tabsContainer">
<ul class="tabList">
<li class="<?php echo $collection == 'open_content' ? 'active' : '' ?>">
</i> Open Content
</li>
<li class="<?php echo $collection == 'images' ? 'active' : '' ?>">
</i> Images
</li>
</ul>
</div>
</div><!--end of header-->
<!-------------------------beginning of main section where seach results will display-------------------------->
<?php
if($collection == "open_content") {
$filters = new filterContentProvider($conn);
}
else {
$filters = new filterImageProvider($conn);
}
if($collection == "open_content") {
$filterType = $filters->getType($conn);
$filterSubject = $filters->getSubject($conn);
$filterOrigin = $filters->getOrigin($conn);
$fitlerLicense = $filters->getLicense($conn);
$filterReviewed = $filters->getReviewed($conn);
echo "<div class='filterContainer'>
<div class='filterContent'>
<div class='filter'>
$filterType
</div>
<div class='filter'>
$filterSubject
</div>
<div class='filter'>
$filterOrigin
</div>
<div class='filter'>
$fitlerLicense
</div>
<div class='filter'>
$filterReviewed
</div>
</div>
</div>";
}
else {
$imageFilterOrigin = $filters->getImageOrigin($conn);
$imageFilterLicense = $filters->getImageLicense($conn);
echo "<div class='filterContainer'>
<div class='filterContent'>
<div class='filter'>
$imageFilterOrigin
</div>
<div class='filter'>
$imageFilterLicense
</div>
</div>
</div>";
}
?>
<div class="mainResultsSection">
<?php
if($collection == "open_content") {
$resultsProvider = new siteResultsProvider($conn);
$pageSize = 25;
}
else {
$resultsProvider = new imageResultsProvider($conn);
$pageSize = 50;
}
$numResults = $resultsProvider->getNumResults($term);
echo "<p class='resultsCount'>" . number_format($numResults) . " results found</p>";
echo $resultsProvider->getResultsHTML($page, $pageSize, $term);
?>
</div>
<div class="paginationContainer">
<div class="pageButtons">
<div class="pageNumberContainer">
<img src="images/pageStart.png" alt="Start of page image">
</div>
<?php
$pagesToShow = 10;
$numPages = ceil($numResults / $pageSize);
$pagesLeft = min($pagesToShow, $numPages);
$currentPage = $page - floor($pagesToShow / 2);
if($currentPage < 1) {
$currentPage = 1;
}
if($currentPage + $pagesLeft > $numPages + 1) {
$currentPage = $numPages + 1 - $pagesLeft;
}
while($pagesLeft != 0 && $currentPage <= $numPages) {
if($currentPage == $page) {
echo "<div class='pageNumberContainer'>
<img src='images/pageSelected.png' alt='selected page page image'/>
<span class='pageNumber'>$currentPage</span>
</div>";
}
else {
echo "<div class='pageNumberContainer'>
<a href='search.php?term=$term&collection=$collection&page=$currentPage'>
<img src='images/page.png' alt='pages image'/>
<span class='pageNumber'>$currentPage</span>
</a>
</div>";
}
$currentPage++;
$pagesLeft--;
}
?>
<div class="pageNumberContainer">
<img src="images/pageEnd.png" alt="End of page image">
</div>
</div>
</div><!--end of pagination container-->
</div><!--end of wrapper-->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.7/dist/jquery.fancybox.min.js"></script>
<script src="https://unpkg.com/masonry-layout#4/dist/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
It seems like you'd want to do a couple of things to get this working.
If you want the results to be asynchronous:
Add an onchange event to you select inputs. (something like onchange="addFilter('type', this.value)") See https://www.w3schools.com/jsref/event_onchange.asp
Have the onchange function (addFilter) send the filters and query string back to your PHP script via an AJAX request. If you're using jQuery, the get method would work for you. https://api.jquery.com/jquery.get/
Pull the new results in PHP using the $_GET parameters you've passed. (Like you are already doing in your script.) You'll want to echo out just the results--not the navigation and other elements of the page.
Update the search results on the page using (something like $('#myContainer').html(results); in jQuery)
Additionally, it would be good to update the URL params in the location bar How do I modify the URL without reloading the page?
Here's a really simple example:
test.php
<?php
// Look up the results here
// You'll probably want to do something more performant that this; it's just a lazy example. :)
// ...
$query = $this->conn->prepare("SELECT type, COUNT(*) as total FROM oer_search WHERE type LIKE :type AND subject LIKE :subject GROUP BY type");
$query->execute([
'type' => isset($_GET['type'] ? $_GET['type'] : '%',
'subject' => isset($_GET['subject'] ? $_GET['subject'] : '%',
]);
// ...
?>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery-3.4.1.min.js"></script>
<script>
function addFilter(name, value) {
var url = '/test.php?';
var urlParams = new URLSearchParams(window.location.search);
var keys = urlParams.keys();
for(key of keys) {
if (key == name) {
continue;
}
url += key + '=' + urlParams.get(key) + '&';
}
url += name + '=' + value;
window.history.pushState({}, "", );
$.get(url, function(data) {
$('#results').html(data);
});
}
</script>
</head>
<body>
<select onchange="addFilter('type', this.value)">
<option></option>
<option>value 1</option>
<option>value 2</option>
</select>
<select onchange="addFilter('subject', this.value)">
<option></option>
<option>value 1</option>
<option>value 2</option>
</select>
<div id="results"></div>
</body>
</html>
If you don't care/want the page to reload:
Just make the onchange event submit the form with the search parameters again. If you use jQuery, the submit method would work. Be sure to select the options appropriately in the select inputs, or they'll clear out each time (making it impossible to set more than one).

Bootstrap Carousel to display text

I want to display long notes on bootstrap carousel. the notes will be fetched from mySql database. Since the notes are long, i need to split them using number of words then display them in the carousel slides. the problems is that am not able to display the splitted text in different slides. the following is what i have done:
<div class="col-md-6 ">
<div class="panel panel-primary">
<div class="panel-heading">Lecture</div>
<!-- Slider News by Carousel -->
<div id='myCarousel' class='carousel slide' data-ride='carousel'>
<ol class='carousel-indicators'>
<?php
include "config/koneksi.php";
$query = "select notes from notes where Note_ID = 34";
$res = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($res)) {
$w = $row['notes'];
$arr2 = str_split($w, 500);
}
//var_dump($arr2);
$max = sizeof($arr2);
$slides = '';
$Indicators = '';
$counter = 0;
?>
</ol>
<div class='carousel-inner'>
<?php
for ($x = 0; $x <= $max; $x++) {
if ($x == 0) {
echo "<div class='item active'>";
echo $arr2[$x]++;
echo "</div>";
} else {
echo "<div class='item'>";
if (!isset($arr2[$x])) {
$arr2[$x] = 0;
}
echo $arr2[$x]++;
echo "</div>";
}
}
echo "</div>";
echo "<a class='left carousel-control' href='#myCarousel' data-slide='prev'>‹</a>";
echo "<a class='right carousel-control' href='#myCarousel' data-slide='next'>›</a>";
echo "</div>";
echo "<!-- End Slider Caraousel-->";
?>
</div>
</div>
</div>
</div>
the result:
the result

While loop use variable 2 times

Hello guys I got a for loop cicle that prints me divs and information from SQL, I print the slider fields with the settings on the mysql like, Slider number, Field postion and so on, the problem is I have a Modal Bootstrap to be printed aswell but I cant print it inside the currently loop .
My question is, is there anyway to store a variable from a for cicle so it can be reutilized?
There is the code
$ID=$row['ID'];
$sql = "SELECT NUM_Slides as valmax FROM slider_settings,Paginas, slider_config where slider_settings.ID = $ID and Paginas.ID= $ID and slider_config.ID=$ID";
$sqlconnect =$connect->query($sql);
$sqlresult =$sqlconnect->fetch_assoc();
for ($k = 1 ; $k <= $sqlresult['valmax']; $k++){
echo "<div class='slider1'>";
$sql1 = "SELECT P$k as campos, tituloP$k as titulo FROM slider_settings, Paginas,slider_config where slider_settings.ID = $ID and Paginas.ID= $ID and slider_config.ID = $ID";
$sqlconnect1 =$connect->query($sql1);
$sqlresult1 =$sqlconnect1->fetch_assoc();
echo "<div class='titulo'>
<h2>$sqlresult1[titulo]</h2>
</div>";
for ($l = 1 ; $l <= $sqlresult1[campos]; $l++){
$campo = "SELECT Butao,Titulo,Texto FROM slider_config, Paginas, slider_settings where slider_config.ID = $ID and Paginas.ID = $ID and slider_settings.ID =$ID and P_NUM = $k and Campo = $l";
$sqlconnect2 = $connect->query($campo);
$sqlresult2 = $sqlconnect2->fetch_assoc();
echo "<div class='part' id='part".$l."'>
<div id='imagem' class='button' data-toggle='modal' data-target='#myModal".$l."'>
<img src='data:image/png;base64," . base64_encode($sqlresult2['Butao']) . "'/>
</div>
<div id='titulo'>
<h4>$sqlresult2[Titulo]</h4>
</div>
<div id='texto'>
$sqlresult2[Texto]
</div>
</div>";
}
echo "</div>";
}
and There is the code that cant printed inside of the div or modal wont display
$modal = "SELECT Titulo_modal , Imagem_modal , Texto_modal FROM modal_settings , Paginas where modal_settings.ID = $ID and Paginas.ID= $ID and P_NUM_modal = $k and Campo_modal = $l";
$sqlconnect33 =$connect->query($modal);
$sqlresult33 =$sqlconnect33->fetch_assoc();
for ($n = 1 ; $n <= $sqlresult1[campos]; $n++){
echo "<div class='modal fade' id='myModal".$n."'>
<div class='modal-dialog modal-lg'>
<div class='modal-content'>
<div class='modal-header'>
<h4 class ='titulopopup'>$sqlresult33[Titulo_modal]</h4>
<button type='button' class='close' data-dismiss='modal'>
<span aria-hidden='true'>×</span></button>
</div>
<div class='modal-body'>
<div class='imagem'>
<img src='data:image/png;base64," . base64_encode($sqlresult33['Imagem_modal']) . "'/>
</div>
<div class='texto'>
$sqlresult33[Texto_modal]
</div>
</div>
</div>
</div>
</div>";
}
NOTE : the $ID is comming from another file :) and its work fine the first half of the code
maybe create array like that
$array = [];
for ($n = 1 ; $n <= $sqlresult1[campos]; $n++) {
$array[$k] = $i;
}
this way u can reuse your var stored in array in other for loop like
foreach ($array as $k => $i) {
// and u get all your var :)
}
with your code u can do somethings like
$ID=$row['ID'];
// here
$array = [];
//
$sql = "SELECT NUM_Slides as valmax FROM slider_settings,Paginas, slider_config where slider_settings.ID = $ID and Paginas.ID= $ID
and slider_config.ID=$ID";
$sqlconnect =$connect->query($sql);
$sqlresult =$sqlconnect->fetch_assoc();
for ($k = 1 ; $k <= $sqlresult['valmax']; $k++){
echo "<div class='slider1'>";
$sql1 = "SELECT P$k as campos, tituloP$k as titulo FROM slider_settings, Paginas,slider_config where slider_settings.ID = $ID and Paginas.ID= $ID and slider_config.ID = $ID";
$sqlconnect1 =$connect->query($sql1);
$sqlresult1 =$sqlconnect1->fetch_assoc();
echo "<div class='titulo'>
<h2>$sqlresult1[titulo]</h2>
</div>";
for ($l = 1 ; $l <= $sqlresult1[campos]; $l++){
// here
$array[$k] = $l;
$campo = "SELECT Butao,Titulo,Texto FROM slider_config, Paginas, slider_settings where slider_config.ID = $ID and Paginas.ID = $ID and slider_settings.ID =$ID and P_NUM = $k and Campo = $l";
$sqlconnect2 = $connect->query($campo);
$sqlresult2 = $sqlconnect2->fetch_assoc();
echo "
<div class='part' id='part".$l."'>
<div id='imagem' class='button' data-toggle='modal' data-target='#myModal".$l."'>
<img src='data:image/png;base64," . base64_encode($sqlresult2['Butao']) . "'/>
</div>
<div id='titulo'>
<h4>$sqlresult2[Titulo]</h4>
</div>
<div id='texto'>
$sqlresult2[Texto]
</div>
</div>";
}
echo "</div>";
}

How to put a Div inside an if statement

Hi i have a code that displays title, date and location. I want it to put on a div, unfortunately there is some wrong in my code and it loops my div.
I just want all may data to be inside "may-container" i just don't know how to create this container.
Hope you could help me with this. Thanks
<div class="may-container">
<div class="May">
title
date
location
</div>
<div class="May">
title
date
location
</div>
</div>
Here is my code
$counter = 0;
while ( $startdate <= $enddate) {
if ( date("F",strtotime($result['date'])) == "May" && date("m, Y",strtotime($result['date'])) >= date("m, Y") )
{
if ($counter < 1)
{
echo "<div class='May-container'>";
$counter++;
}
echo "<div class= 'May'>";
echo $result['title'],"<br>";
echo date ('F \ j,\ Y',strtotime($result['date']) ), "<br>";
echo $result['location'];
echo "</div>";
}
$startdate = strtotime("+120 day", $startdate);
}
if your code date("F",strtotime($result['date'])) produces a month in words then why do you have to put if and else?
why not:
while ( $startdate <= $enddate) {
echo "<div class='" . date('F',strtotime($result['date'])) . "'>";
echo $result['title'],"<br>";
echo date ('F \ j,\ Y',strtotime($result['date']) ), "<br>";
echo $result['location'];
echo "</div>";
$startdate = strtotime("+120 day", $startdate);
}
EDIT: to answer your comment, you can try this code:
This code is only applicable if your Data is sorted out by date
$last_month = '';
$is_first = true;
while ( $startdate <= $enddate) {
if($last_month != date('F',strtotime($result['date']))){
echo '</div>';
$is_first = true;
}
if($is_first){
$last_month = date('F',strtotime($result['date']));
echo "<div class='". strtolower($last_month) . "-container'>";
$is_first = false;
}
echo "<div class='" . date('F',strtotime($result['date'])) . "'>";
echo $result['title'],"<br>";
echo date ('F \ j,\ Y',strtotime($result['date']) ), "<br>";
echo $result['location'];
echo "</div>";
$startdate = strtotime("+120 day", $startdate);
}
if the code above code runs as what i expected(sorry i didnt run it for i dont have enough time to) it will yields something like:
<div class="may-container">
<div class="May">
title
date
location
</div>
<div class="May">
title
date
location
</div>
</div>
<div class="june-container">
<div class="June">
title
date
location
</div>
<div class="June">
title
date
location
</div>
</div>

While loop returning data

In the code below, I'm pulling all upcoming training classes from my database. I'm checking to see if the endDate has passed and I'm also checking if the status !='2'
I want this to return the 4 most recent results. It works fine until statusdoes =2. I understand that the loop is technically running 4 times, but only displaying the results with status !='2'
How can I change this so that if status = '2' the loop will continue until it finds 4 results that meet the criteria?
<?php
$today = date("Y-m-d");
$count = 0;
$sth = $dbh->query('SELECT * from training ORDER BY startDate ASC');
$sth->setFetchMode(PDO::FETCH_ASSOC);
while($count <= 4 && $row = $sth->fetch()) {
if($row['endDate'] > $today && $row['status'] != '2') {?>
<li>
<img class="post_thumb" src="/images/img.jpg" alt="" />
<div class="post_description">
<small class="details">
<?php echo date("m/d/Y", strtotime($row['startDate'])) . ' - ' . date("m/d/Y", strtotime($row['endDate'])) ?>
</small>
<a class="post_caption" href="/register.php?course_id=<?php echo $row['courseId'] . '&id=' . $row['id'] ?>"><?php echo $row['title'] ?></a>
</div>
</li>
<?php }
$count++;
}
?>
You must put the $count++ inside the if loop, otherwise it will always get incremented.
As in:
<?php
$today = date("Y-m-d");
$count = 0;
$sth = $dbh->query('SELECT * from training ORDER BY startDate ASC');
$sth->setFetchMode(PDO::FETCH_ASSOC);
while($count <= 4 && $row = $sth->fetch()) {
if($row['endDate'] > $today && $row['status'] != '2') {?>
<li>
<img class="post_thumb" src="/images/img.jpg" alt="" />
<div class="post_description">
<small class="details">
<?php echo date("m/d/Y", strtotime($row['startDate'])) . ' - ' . date("m/d/Y", strtotime($row['endDate'])) ?>
</small>
<a class="post_caption" href="/register.php?course_id=<?php echo $row['courseId'] . '&id=' . $row['id'] ?>"><?php echo $row['title'] ?></a>
</div>
</li>
<?php
$count++;
}
}
?>
You can break out out of the loop, if its four
while($row = $sth->fetch()) {
....
if($row['status']=='2' && $count >="4") break;
$count++;
}

Categories