<?php
$host='localhost';
$user='root';
$password='root';
$database='database';
$startindex=#$_REQUEST['seek'];
$db=mysql_connect($host, $user, $password)
or die ("Impossibile connettersi al server $host");
mysql_select_db($database, $db)
or die ("Impossibile connettersi al database $database");
$query="SELECT * FROM ordini_master";
$dbResult=mysql_query($query, $db);
$AffectedRows=mysql_affected_rows($db);
mysql_data_seek($dbResult, $startindex);
$row=mysql_fetch_row($dbResult);
foreach($row as $k=>$v)
{
$myfield=mysql_fetch_field($dbResult, $k);
print($myfield->name . " : $v <br/>");
}
mysql_free_result($dbResult);
mysql_close($db);
print("<br/>Seleziona il record<br/>");
for($index=0; $index<$AffectedRows; $index++)
{
print("<a href=\"{$_SERVER['PHP_SELF']}?seek=$index\" >" .
($index+1) . "</a> ");
}
?>
This code allow the navigation between a query records, so it create a page foreach record in database and so shows one record time. How can i modify that code to paging every 10 records? So i want to show 10 records time and create a page for the next.
Sorry for my english (I'm italian) , i hope you can help me.
What you need first is the LIMIT statement from mysql. MySql states:
The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be nonnegative integer constants (except when using
prepared statements).
With two arguments, the first argument specifies the offset of the
first row to return, and the second specifies the maximum number of
rows to return. The offset of the initial row is 0 (not 1):
As for how to implement it in your code I could not have written a better answer as the one found here.
Use LIMIT to get as many records as you wish.
Example:
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
Here is your modified code. This should work for your.
I haven't tested it but give it a try:
<?php
$host='localhost';
$user='root';
$password='root';
$database='database';
$startindex=(isset($_REQUEST['seek']) ? $_REQUEST['seek'] : 0);
$db=mysql_connect($host, $user, $password)
or die ("Impossibile connettersi al server $host");
mysql_select_db($database, $db)
or die ("Impossibile connettersi al database $database");
$queryCnt = "SELECT count(*) as cnt FROM ordini_master";
$CntRow=mysql_fetch_row(mysql_query($query, $db));
$CntData = $CntRow[0];
$step = 10;
$query="SELECT * FROM ordini_master LIMIT $startindex, $step";
$result=mysql_query($query, $db);
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $k=>$v) {
$myfield=mysql_fetch_field($result, $k);
print($myfield->name . " : $v <br/>");
}
}
mysql_free_result($result);
mysql_close($db);
print("<br/>Seleziona il record<br/>");
for($index=0; $index<$CntData; $index=$index+$step) {
print("<a href=\"{$_SERVER['PHP_SELF']}?seek=$index\" >" .
($index+1) . "</a> ");
}
Use the information from tadman too.
It's very important to do something to prevent SQL injection and it's also necessary to use PDO or the mysqli extension because the mysql extension will not longer be supported.
You can use COUNT to display your records and create pages
function getLimitData($start,$limit){
//getting all items
$db = new PDO('mysql:host=localhost; dbname=data','root','');
$results = $db->query("SELECT * FROM table ORDER BY ID DESC limit $start,$limit");
$results = $results->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
//database connection
$db = new PDO('mysql:host=localhost; dbname=data','root','');
//pagination pages
$nav_counter = basename($_SERVER['SCRIPT_FILENAME']);
$page_counter = $nav_counter;
$nav_counter = rtrim($nav_counter, ".php");
$cPage = $page_counter + 1;
//creating next pages
$first_next = $nav_counter + 1 ;
$sec_next = $first_next + 1 ;
$third_next = $sec_next + 1 ;
$fourth_next = $third_next + 1 ;
$fifth_next = $fourth_next + 1 ;
$sixth_next = $fifth_next + 1 ;
$seventh_next = $sixth_next + 1 ;
$next_page = $seventh_next + 1;
//creating previous pages
$first_prev = $nav_counter - 1 ;
$sec_prev = $nav_counter - 2 ;
$third_prev = $nav_counter - 3 ;
$fourth_prev = $nav_counter - 4 ;
$fifth_prev = $nav_counter - 5 ;
$sixth_prev = $nav_counter - 6 ;
$seventh_prev = $nav_counter - 7 ;
//row count
$tableExists = $db->tableExist();
$ROW_COUNT = $db->getRowCount();
$numRows= 9; //number of items to be displayed
//last page
//last page
$last_page = ($ROW_COUNT / $numRows) - 1;
if(!is_int($last_page)){
$last_page = (int)$last_page + 1;
}
$pageNate = '';
if($ROW_COUNT <= $numRows){
$pageNate = 'class="hide"';
}else{
$pageNate = 'class="exist"';
}
//displaying torrents
$start = 0;
$limit = $numRows;
if ($page_counter !== 'index.php') {
$start = ($limit * $nav_counter);
}
//getting number of rows left in the table
$rows_left = $db->getLimitData($start, $limit);
$number_rows = 0;
foreach ($rows_left as $r) {
$number_rows = $number_rows + 1;
}
if ($number_rows < $numRows) {
$limit = $number_rows;
}
$items = $db->getLimitData($start, $limit);
?>
displaying item
<ol>
<?php foreach($items as $item) : ?>
<li><php echo $item['Value']; ?></li>
<?php endforeach; ?>
</ol>
pagination code
<?php
$pages = array();
for ($counter = 1; $counter <= $last_page; $counter++) {
$pages[] = $counter;
}
//storing pages in array and creating a page if it doesn't exist
foreach ($pages as $key) {
$page = $key.'.php';
//if page doesn't exists create page
if(file_exists($page)== false && $key <= $last_page){
copy('index.php', $page);
}
}
?>
<p class="pagenav" >
<a href="index.php" <?php if ($page_counter == 'index.php') {echo 'class="hide"';} ?>><<</a>
<a href="<?php if ($page_counter == '1.php') {echo 'index.php';}else{echo "$first_prev".".php";} ?>" <?php if ($page_counter == 'index.php') {echo 'class="hide"';} ?>><</a>
<a href="<?php echo "$seventh_prev".".php"; ?>" <?php if($seventh_prev <= 0){echo 'class="hide"';} ?>><?php echo $seventh_prev;?></a>
<a href="<?php echo "$sixth_prev".".php"; ?>" <?php if($sixth_prev <= 0){echo 'class="hide"';} ?>><?php echo $sixth_prev;?></a>
<a href="<?php echo "$fifth_prev".".php"; ?>" <?php if($fifth_prev <= 0){echo 'class="hide"';} ?>><?php echo $fifth_prev;?></a>
<a href="<?php echo "$fourth_prev".".php"; ?>" <?php if($fourth_prev <= 0){echo 'class="hide"';} ?>><?php echo $fourth_prev;?></a>
<a href="<?php echo "$third_prev".".php"; ?>" <?php if($third_prev <= 0){echo 'class="hide"';} ?>><?php echo $third_prev;?></a>
<a href="<?php echo "$sec_prev".".php"; ?>" <?php if($sec_prev <= 0){echo 'class="hide"';} ?>><?php echo $sec_prev;?></a>
<a href="<?php echo "$first_prev".".php"; ?>" <?php if($first_prev <= 0 ){echo 'class="hide"';} ?>><?php echo $first_prev;?></a>
<a <?php if ($page_counter == 'index.php') {echo 'class="hide"';}else{ echo 'id="here"';} ?>><?php echo $nav_counter; ?></a>
<a href="<?php echo $first_next.'.php'; ?>" <?php if($first_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $first_next;?></a>
<a href="<?php echo "$sec_next".".php"; ?>" <?php if($sec_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $sec_next;?></a>
<a href="<?php echo "$third_next".".php"; ?>" <?php if($third_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $third_next;?></a>
<a href="<?php echo "$fourth_next".".php"; ?>" <?php if($fourth_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $fourth_next;?></a>
<a href="<?php echo "$fifth_next".".php"; ?>" <?php if($fifth_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $fifth_next;?></a>
<a href="<?php echo "$sixth_next".".php"; ?>" <?php if($sixth_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $sixth_next;?></a>
<a href="<?php echo "$seventh_next".".php"; ?>" <?php if($seventh_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $seventh_next;?></a>
<a href="<?php echo "$first_next".".php"; ?>" <?php if($first_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>>></a>
<a href="<?php echo $last_page.'.php'; ?>" <?php if($nav_counter == $last_page){echo 'class="hide"';}else{echo 'class="exist"';} ?>>>></a>
</p>
Related
I have listing in my HTML which is displayed from database. My listing code is like below:
<?php
require('admin/db_config.php');
$sql = "SELECT * FROM image_gallery";
$images = $mysqli->query($sql);
while($image = $images->fetch_assoc()){
?>
<div class="aamir"><span><img style="height:40px; width:55px; " class="img-responsive" alt="" src="admin/uploads/<?php echo $image['image'] ?>" /></span><small><?php echo $image['title']; ?></small><strong style="width:40%; height: 35%;"><em class="icon icon-chevron-down"></em><p style="margin-top: -5%;"> <?php echo $image['description']; ?> </p></strong>
<a
class="zayan" target="_blank" href="<?php echo $image['url']; ?>">VISIT</a>
</div>
<?php } ?>
Now I have given pagination for the same because the data is too much and I want it to go to next page. So I have given pagination. Pagination code is below:
<?php
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("localhost","root","","sample");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM image_gallery";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM image_gallery LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($res_data)){
//here goes the data
}
mysqli_close($conn);
?>
<ul class="pagination">
<li>First</li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
Prev
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
Next
</li>
<li>Last</li>
</ul>
But still the pagination is not working, no error is shown, the whole data is being displayed in one page and the pagination is like static.
The code I have works absolutely perfectly:
<?
$maxresults = 10;
$total = $row[total];
$pagecount = $total / $maxresults;
if (!isset($_GET['page'])) { $_GET['page'] = '1'; }
$startcount = (($_GET['page'] - 1) * $maxresults + 1);
$stopcount = $startcount + ($maxresults - 1);
$lastTime = null;
$i='0';
$sc = $startcount;
$stmt=$db->prepare("// SELECT STATEMENT");
$stmt->bindParam(':user', $username);
$stmt->execute();
while ( $row = $stmt->fetch() ) {
if (!($sc > $stopcount)) {
$i++;
if( $row['time'] !== $lastTime ) {
if ( $lastTime === NULL ) {
echo '// close of loop';
} else {
echo '// loop grouping as title';
}
$lastTime = $row['time'];
}
if ($i >= $sc) { ?>
// the html to loop
<?
$sc++;
}
}
}
?>
Forward and Back buttons are easy enough to create. if $_GET['page'] * 10 > $total, active the next button, if $_GET['page'] > 1 activate previous button.
What I can't figure out is the correct formula and loop so I can always display the correct number of "page numbered" links. I want to always show 5 based on the 3rd number. So 1 would should 5 links: 1 - 5, 2 would also show 1 - 5, as would 3, 4 would show 2 - 6, 5 would show 3 - 7.
Now obviously, I could just add 2 and subtract 2 from the current $_GET[page] if the get page is greater than 3, but I need to take into account testing to see if the results go that high. So only if results are greater than 10 should number 2 show, and then if on page 16 pages 17 and 18 should only show if there are 170 and 180 results to display.
Perhaps I have just been staring at the code to long, but I can't seem to get a formula or loop correct in my head to even attempt the code page.
It was a fairly specific question. Wasn't sure if anyone would help with something so specific or not. Guess I learned.
Here is the answer to my own question:
<ul>
<li class="<? if ($_GET['page'] < '2') { echo 'disabled' ; } ?>">
<a href="<?
if ($_GET['page'] == '2') {
echo 'inbox.php';
} else {
echo '?page='.($_GET[page] - 1);
}
?>">Prev</a>
</li> <!-- previous button-->
<li style="<? if ($_GET['page'] - 2 < '1') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] -2); ?>">
<? echo ($_GET[page] -2); ?>
</a>
</li> <!-- the button 2 before current spot if its greater than 0 -->
<li style="<? if ($_GET['page'] - 1 < '1') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] -1); ?>">
<? echo ($_GET[page] -1); ?>
</a>
</li> <!-- the button 1 before current spot if its greater than 0 -->
<li class="disabled">
<? echo $_GET[page]; ?>
</li> <!-- current button disabled -->
<li style="<? if ($total - ($_GET[page] * 10) <= '0') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] + 1); ?>">
<? echo ($_GET[page] +1); ?>
</a>
</li> <!-- the button 1 after current spot if results go that high -->
<li style="<? if ($total - ($_GET[page] + 1) * 10 <= '0') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] + 2); ?>">
<? echo ($_GET[page] + 2); ?>
</a>
</li> <!-- the button 2 after current spot if results go that high -->
<li class="<? if ($total - ($_GET[page] * 10) <= '0') { echo 'disabled'; } ?>">
Next
</li> <!-- the next button if results go that high -->
</ul>
#bruce after seeing your solution, I'd like to give you my own solution.
$page = $_GET['page'];
$max_pages = ceil($total / $maxresults);
$min_pages = 1;
$start = max($min_pages, $page-2);
$end = min($max_pages, $start+2);
$nav = ($page > $min_pages ? '<li><</li>' : '' );
for ($i = $start; $i <= $end; $i++)
$nav .= '<li' . ($i == $page ? 'class="active"' : '' ) . '>' . $i . '</li>';
$nav .= ($page < $max_pages ? '<li>></li>' : '' );
I have set-up a news page which retrieves news from MYSQL news table.
I am trying to identify if the news column is odd or even, so if the news columns is odd or even it will add a class to the div element.
My code is as follows:
<?php
$cat = $_GET['cat'];
$date = $_GET['date'];
if ($date !="") {
$date = explode('-', $date);
$year = $date[1];
$month = $date[0];
$month = date("m", strtotime($month));
$sql = "SELECT * FROM news WHERE year(newsDate) = '$year' AND month(newsDate) = '$month' AND newsState = 1 ORDER BY newsDate DESC";
} else {
$sql = "SELECT * FROM news WHERE newsState = 1 ORDER BY newsDate DESC";
}
$result = $conn->query($sql);
$rows = $result->num_rows;
$pager = new PS_Pagination($conn, $sql, 5, 10, null);
$rs = $pager->paginate();
$num = $rs->num_rows;
if($num >= 1 ){
while($row = $rs->fetch_assoc()){
?>
<div class="news <?php echo $num; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php } } else {
echo "No records found!";
}
if ($rows >= 5) {
echo "<div class='page-nav blog-nav'>";
echo $pager->renderFullNav();
echo "</div>";
}
?>
TAke any flag which maintains odd-even position...
$f = 0; //ADDED THIS LINE
if($num >= 1 ){
while($row = $rs->fetch_assoc()){
if($f%2==0) //ADDED THIS LINE
$class_name = "even"; //ADDED THIS LINE
else //ADDED THIS LINE
$class_name = "odd"; //ADDED THIS LINE
?>
<div class="news <?php echo $class_name; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php $f++; } } else {
echo "No records found!";
}
if($num >= 1 ){
$tr = 1;
while($row = $rs->fetch_assoc()){
if($tr%2 == 0)
{
//then even class
}
else
{
//odd class
}
?>
<div class="news <?php echo $num; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php $tr++; } } else {
echo "No records found!";
}
Use counter variable and check if it is even or odd ?
Create variable, increment that in each loop and check, if $i % 2 is 0 (even) or 1 (odd).
$i = 1;
while($row = $rs->fetch_assoc()){
?>
<div class="news <?php echo $num; echo $i % 2 == 0 ? ' even' : ' odd' ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php
$i++;
}
Take $classname = '';
Get news ID in loop and divide / 2 and compare whether you getting odd / even value. In case odd value add $classname = 'oddCLASS' and in case even value add $classname = 'evenCLASS' and updare class = $classname wherever you required.
This way it will automatically update dynamic class.
so the fastest way to do this is just by using a boolean:
$odd = false;
while ( .... )
{
echo ($odd = !$odd) ? 'odd' : 'even';
}
No need to keep a counter for that, no need for a modulo and it keeps the code pretty clean. My preferred way unless you need to keep a counter. And even then: $counter & 1 == 1 is faster than $counter % 2 == 1 and does exactly the same.
Simple explanation:
echo ($odd = !$odd) ? 'odd' : 'even';
// will become
$odd = ! $odd; // it flips the boolean
if ($odd)
echo 'odd';
else
echo 'even';
I use below code for pagination.How to add first,previous,next,last links in pagination.
Only 9 paging numbers should allow in pagination.
EX : First , Previous . ( 9 paging numbers) ,Next ,Last
I have attached image for reference.
<?php
$page = $_GET['url_page'];
$limit =5;
if($page==""){
$page =1;
$start_limit =0;
$end_limit = $page * $limit;
}
else {
$end_limit = $page * $limit;
$start_limit =$end_limit - $limit;
}
$array_count_res = count($result_array);
$choice = ceil($array_count_res /$limit);
$previous_page = $page-1;
$next_page = $page+1;
<?php if($page !=1) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $previous_page; ?>">
Previous</a>
<?php } ?>
<?php for($pa = 0 ;$pa < $choice;$pa++){ ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $pa+1; ?>">
<?php echo $pa+1;echo " "; ?></a>
<?php } ?>
<?php if($page !=$choice) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $next_page; ?>">
Next</a>
<?php } ?>
<?php
for($m=$start_limit;$m < $end_limit;$m++) {
if($result_array[$m]['name'] !="") {
?>
finaly i got answer
<?php
$page = $_GET['url_page'];
$limit =25;
if($page==""){
$page =1;
$start_limit =0;
$end_limit = $page * $limit;
}
else {
$end_limit = $page * $limit;
$start_limit =$end_limit - $limit;
}
$array_count_res = count($contacts);
$choice = ceil($array_count_res /$limit);
$previous_page = $page-1;
$next_page = $page+1;
$first_paging = $page - 2;
$second_paging = $page - 1;
$third_paging = $page + 1;
$four_paging = $page + 2;
$last_page =$choice -$page;
for($m=$start_limit;$m < $end_limit;$m++) {
?>
<tr><td> data</td></tr>
<?php } ?>
<!---pagination starts----->
<tr><td id="importcaontact_page" >
<?php if($page > 3) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/1">
«First</a>
<?php } ?>
<?php if($page !=1) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $previous_page; ?>">
«Previous</a>
<?php } ?>
<?php if($first_paging > 0 ) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $first_paging; ?>">
<?php echo $first_paging; ?></a>
<?php } ?>
<?php if($second_paging > 0 ) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?><?php echo $second_paging; ?>">
<?php echo $second_paging; ?></a>
<?php } ?>
<?php echo $page; ?>
<?php if($third_paging <= $choice ) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $third_paging; ?>">
<?php echo $third_paging; ?></a>
<?php } ?>
<?php if($four_paging <= $choice ) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $four_paging; ?>">
<?php echo $four_paging; ?></a>
<?php } ?>
<?php if($page !=$choice) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $next_page; ?>">
Next »</a>
<?php } ?>
<?php if($last_page > 1) { ?>
<a href="<?php echo $_SERVER['PHP_SELF'];?>/<?php echo $choice; ?>">
Last »</a>
<?php } ?>
</td></tr>
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++;
}