I have standings script, I used for soccer.
As we know in soccer there are:
Group’s games depend in points
And
Head to head match which point table not important
My script deal with both kinds of games in same way.
I mean the point table appears in both types.
My question:
I want let points table visible in games depend in point and hide the table in head to head games.
I have (conference, season, and division id) for each game.
Is there any way to hide point table in head to head games according to (conference, season, and division id)?
Notes: the table that I want to work in it is “ standingstable “
I will put standings.php and if you need setting.php file i can add it later
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Current Standings</title>
<style type="text/css">
body, td {
font: 13px "Lucida Grande", "Lucida Sans Unicode", Tahoma, Verdana;
}
a, a:visited {
border-bottom: 1px solid #69c;
color: #00019b;
text-decoration: none;
}
th {
text-align: left;
}
.standingstable {
width: 760px;
}
.gamestable, .scorestable, .teamhistory {
border-collapse: collapse;
margin-top: 10px;
margin-bottom: 10px;
width: 700px;
}
.gamestable td, .gamestable th, .scorestable td, .scorestable th, .teamhistory td, .teamhistory th {
padding: 5px;
border: 1px solid black;
}
.gamestable tr, .scorestable tr, .teamhistory tr {
vertical-align: top;
}
</style>
</head>
<body>
<h2>Current Standings</h2>
<?php
require "settings.php";
if (isset($_GET['conf'])) {
$confid = intval($_GET['conf']);
}
else {
$confid = 0;
}
if (isset($_GET['team'])) {
$team = intval($_GET['team']);
}
else {
$team = 0;
}
if (isset($_GET['history'])) {
$history = intval($_GET['history']);
}
else {
$history = 0;
}
mysql_connect($sportsdb_host,$sportsdb_user,$sportsdb_pass);
#mysql_select_db($sportsdb_db) or die( "Unable to select database");
include 'standings_functions.php';
if ($history > 0) {
// We need the team ID and the conference ID too
if ($confid < 1 || $team < 1) {
die ('Not enough information supplied');
}
print '<p>Back to the conference standings</p>' . "\n";
print '<p>Back to the team schedule</p>' . "\n";
$query = 'SELECT teamname, masterteam FROM sportsdb_teams WHERE teamid = ' . $team . ' LIMIT 1';
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
die('No such team exists');
}
else {
$teamname = mysql_result($result,0,"teamname");
$masterteam = mysql_result($result,0,"masterteam");
}
print '<h3>' . $teamname . ' history</h3>' . "\n";
$query = 'SELECT sportsdb_teams.teamid, sportsdb_teams.teamname, sportsdb_teams.teamwins, sportsdb_teams.teamlosses, sportsdb_teams.teamties, sportsdb_teams.teamforfeits,
sportsdb_divs.divname,
sportsdb_conferences.confname, sportsdb_conferences.confid,
sportsdb_seasons.seasonname
FROM sportsdb_teams, sportsdb_divs, sportsdb_conferences, sportsdb_seasons
WHERE sportsdb_teams.masterteam = ' . $masterteam . '
AND sportsdb_teams.teamdiv = sportsdb_divs.divid
AND sportsdb_divs.conference = sportsdb_conferences.confid
AND sportsdb_conferences.season = sportsdb_seasons.seasonid
ORDER BY sportsdb_seasons.seasonorder';
$result = mysql_query($query) or die ('Error in query: ' . $query);
?>
<table class="teamhistory">
<tr>
<th>Season</th>
<th>Team</th>
<th>Conference</th>
<th>Division</th>
<th>Wins</th>
<th>Losses</th>
<?php if ($show_ties) { ?><th>Ties</th><?php } ?>
<?php if ($forfeits) { ?><th>Forfeits</th><?php } ?>
</tr>
<?php
while ($teams = mysql_fetch_array($result, MYSQL_ASSOC) ) {
$seasonname = htmlspecialchars($teams['seasonname'], ENT_QUOTES);
print "\t" . '<tr>' . "\n";
print "\t\t" . '<td>' . $seasonname . '</td>' . "\n";
print "\t\t" . '<td><a href="?team=' . $teams['teamid'] . '&conf=' . $teams['confid'] . '">' . $teams['teamname'] . '</td>' . "\n";
print "\t\t" . '<td>' . $teams['confname'] . '</td>' . "\n";
print "\t\t" . '<td>' . $teams['divname'] . '</td>' . "\n";
print "\t\t" . '<td>' . $teams['teamwins'] . '</td>' . "\n";
print "\t\t" . '<td>' . $teams['teamlosses'] . '</td>' . "\n";
if ($show_ties) {
print "\t\t" . '<td>' . $teams['teamties'] . '</td>' . "\n";
}
if ($forfeits) {
print "\t\t" . '<td>' . $teams['teamforfeits'] . '</td>' . "\n";
}
print "\t" . '</tr>' . "\n";
}
print '</table>' . "\n";
}
elseif ($team > 0) {
// We need the conference ID too
if ($confid < 1) {
die ('Not enough information supplied');
}
print '<p>Back to the conference standings</p>' . "\n";
print '<h3>' . get_team_name($team). ': full schedule and scores</h3>' . "\n";
print '<p>Team history</p>' . "\n";
sls_team_schedule($team);
}
elseif ($confid > 0) {
// Allow sorting to occur
if (isset($_GET['sort'])) {
$standings_sort = intval($_GET['sort']);
}
else {
$standings_sort = 0;
}
switch ($standings_sort) {
/*
Available sort fields:
Name: teamname
Wins: teamwins
Losses: teamlosses
Ties: teamties
Forfeits: teamforfeits
Runs for: teamrf
Runs against: teamra
Games behind: gamesbehind
Points: points
Winning percentage: winningpct
Custom tie break: teamorder
Separate the fields by commas and always specify a sort order as DESC for descending and ASC for ascending
*/
case 1: // Sort by team name
$sort_order = "teamname ASC"; break;
case 2: // Sort by wins
$sort_order = "teamwins DESC, teamties DESC, teamlosses ASC, teamorder DESC"; break;
case 3: // Sort by losses
$sort_order = "teamlosses DESC, teamwins ASC, teamties ASC, teamorder DESC"; break;
case 4: // Sort by ties
$sort_order = "teamties DESC, teamwins DESC, teamlosses ASC, teamorder DESC"; break;
case 5: // Sort by forfeits
$sort_order = "teamforfeits DESC, teamwins ASC, teamties ASC, teamorder DESC"; break;
case 6: // Sort by games played
$sort_order = "gamesplayed DESC, teamwins DESC, teamties DESC, teamlosses ASC, teamorder DESC"; break;
case 7: // Sort by runs for
$sort_order = "teamrf DESC, teamwins ASC, teamties DESC, teamlosses ASC, teamorder DESC"; break;
case 8: // Sort by runs against
$sort_order = "teamra DESC, teamwins DESC, teamties ASC, teamlosses DESC, teamorder DESC"; break;
case 9: // Sort by games behind
$sort_order = "gamesbehind ASC, teamties DESC, teamwins DESC, teamlosses ASC, teamorder DESC"; break;
case 10: // Sort by points
$sort_order = "points DESC, teamwins DESC, winningpct DESC, teamorder DESC"; break;
default: // Sort by winning percentage
$standings_sort = 0; $sort_order = "winningpct DESC, teamorder DESC";
}
$division_sort = "";
// Different winning percentage calculations
switch ($winning_pct_calc) {
case 2: // Treating a tie as a half win
$winning_pct_formula = '((teamwins + (teamties / 2)) / (teamwins + teamties + teamlosses + teamforfeits))';
break;
case 3: // Treating winning percentage as number of points relative to total possible points
$winning_pct_formula = '((teamwins * ' . $points_win . ' + teamforfeits * ' . $points_forfeit . ' + teamties * ' . $points_tie . ') / ((teamwins + teamties + teamlosses + teamforfeits) * ' . $points_win . '))';
break;
default: // Ignoring ties
$winning_pct_formula = '(teamwins / (teamwins + teamlosses + teamforfeits))';
}
// print the conference name
$resultconf = mysql_query("SELECT sportsdb_conferences.confname, sportsdb_seasons.seasonid, sportsdb_seasons.seasonname FROM sportsdb_conferences, sportsdb_seasons WHERE sportsdb_conferences.confid = $confid AND sportsdb_conferences.season = sportsdb_seasons.seasonid LIMIT 1");
$confname = #mysql_result($resultconf, 0, 'confname') or die ('No such conference');
$seasonid = mysql_result($resultconf, 0, 'seasonid');
$seasonname = mysql_result($resultconf, 0, 'seasonname');
$seasonname = htmlspecialchars($seasonname, ENT_QUOTES);
print '<h2>' . $confname . ' (' . $seasonname . ')</h2>' . "\n";
print '<p>Back to conference list</p>';
print "\n" . '<hr />' . "\n";
// Get the divisions
$resultconf = mysql_query("SELECT divname, divid FROM sportsdb_divs WHERE conference = $confid ORDER BY divorder");
$numconf = mysql_num_rows($resultconf);
if ($numconf == 0) {
print "<p>No divisions in this conference</p>\n";
}
else {
while ($divs = mysql_fetch_array($resultconf, MYSQL_ASSOC)) {
// Loop through each division
$divname = $divs['divname'];
?>
<h3><?php print $divname; ?></h3>
<table class="standingstable">
<tr>
<td width="25%"><?php if ($standings_sort != 1) print '"; ?><strong>Team Name</strong><?php if ($standings_sort != 1) print ''; ?></td>
<td><?php if ($standings_sort != 6) print '"; ?><strong>GP</strong><?php if ($standings_sort != 2) print ''; ?></td>
<td><?php if ($standings_sort != 2) print '"; ?><strong>Wins</strong><?php if ($standings_sort != 2) print ''; ?></td>
<td><?php if ($standings_sort != 3) print '"; ?><strong>Losses</strong><?php if ($standings_sort != 3) print ''; ?></td>
<?php if ($show_ties) { ?>
<td><?php if ($standings_sort != 4) print '"; ?><strong>Ties</strong><?php if ($standings_sort != 4) print ''; ?></td>
<?php } ?>
<?php if ($forfeit) { ?>
<td><?php if ($standings_sort != 5) print '"; ?><strong>Forfeits</strong><?php if ($standings_sort != 5) print ''; ?></td>
<?php } ?>
<?php if ($show_rfra) { ?>
<td><?php if ($standings_sort != 7) print '"; ?><strong>RF</strong><?php if ($standings_sort != 7) print ''; ?></td>
<td><?php if ($standings_sort != 8) print '"; ?><strong>RA</strong><?php if ($standings_sort != 8) print ''; ?></td>
<?php } ?>
<?php if ($show_gb) { ?>
<td><?php if ($standings_sort != 9) print '"; ?><strong>GB</strong><?php if ($standings_sort != 9) print ''; ?></td>
<?php } ?>
<td><?php if ($standings_sort != 0) print '"; ?><strong>PCT</strong><?php if ($standings_sort != 0) print ''; ?></td>
<?php if ($show_points) { ?>
<td><?php if ($standings_sort != 10) print '"; ?><strong>Points</strong><?php if ($standings_sort != 10) print ''; ?></td>
<?php } ?>
</tr>
<?php
$query = "SELECT COUNT(*) FROM sportsdb_teams WHERE teamdiv = {$divs['divid']}";
$result = mysql_query($query);
$result_exist = mysql_result($result,0);
if ($result_exist) {
$query = "SELECT teamid, teamname, teamwins, teamties, teamlosses, teamforfeits, teamrf, teamra,
(teamwins + teamties + teamlosses + teamforfeits) AS gamesplayed,
(teamwins * $points_win + teamforfeits * $points_forfeit + teamties * $points_tie) AS points,
$winning_pct_formula AS winningpct,
(teamwins - teamlosses - teamforfeits) AS leadervalue
FROM sportsdb_teams
WHERE teamdiv = {$divs['divid']}
ORDER BY leadervalue DESC, teamties DESC LIMIT 1";
$result = mysql_query($query) or die ("Error in query: $query");
$results = mysql_fetch_array($result, MYSQL_ASSOC);
$winningpct = number_format($results['winningpct'], 3);
}
// Show the leader at the top for default sorting (games behind)
if ($standings_sort == 9) {
?>
<tr>
<td><em><?php print $results['teamname']; ?></em></td>
<td><?php print $results['gamesplayed']; ?></td>
<td><?php print $results['teamwins']; ?></td>
<td><?php print $results['teamlosses']; ?></td>
<?php if ($show_ties) { ?>
<td><?php print $results['teamties']; ?></td>
<?php }
if ($forfeit) { ?>
<td><?php print $results['teamforfeits']; ?></td>
<?php }
if ($show_rfra) { ?>
<td><?php print $results['teamrf'];?></td>
<td><?php print $results['teamra'];?></td>
<?php }
if ($show_gb) { ?>
<td>---</td>
<?php } ?>
<td><?php print $winningpct; ?></td>
<?php if ($show_points) { ?>
<td><?php print $results['points'] ?></td>
<?php } ?>
</tr>
<?php }
if ($result_exist) {
$query="SELECT teamid, teamname, teamwins, teamties, teamlosses, teamforfeits, teamrf, teamra,
(teamwins + teamties + teamlosses + teamforfeits) AS gamesplayed,
(teamwins * $points_win + teamforfeits * $points_forfeit + teamties * $points_tie) AS points,
$winning_pct_formula AS winningpct,
((({$results['leadervalue']}) - (teamwins - teamlosses - teamforfeits)) / 2) AS gamesbehind
FROM sportsdb_teams
WHERE teamdiv = {$divs['divid']}";
if ($standings_sort == 9) {
$query .= " AND teamid != {$results['teamid']}";
}
$query .= " AND active = 1" . $division_sort . " ORDER BY $sort_order";
$result=mysql_query($query);
$num=mysql_num_rows($result);
while ($results = mysql_fetch_array($result, MYSQL_ASSOC)) {
$winningpct=number_format($results['winningpct'], 3);
$gamesbehind = number_format($results['gamesbehind'],1);
if ($gamesbehind == "0.0") {
$gamesbehind = "---";
}
?>
<tr>
<td><em><?php print $results['teamname']; ?></em></td>
<td><?php print $results['gamesplayed']; ?></td>
<td><?php print $results['teamwins']; ?></td>
<td><?php print $results['teamlosses']; ?></td>
<?php if ($show_ties) { ?>
<td><?php print $results['teamties']; ?></td>
<?php }
if ($forfeit) { ?>
<td><?php print $results['teamforfeits']; ?></td>
<?php }
if ($show_rfra) { ?>
<td><?php print $results['teamrf']; ?></td>
<td><?php print $results['teamra']; ?></td>
<?php }
if ($show_gb) { ?>
<td><?php print $gamesbehind; ?></td>
<?php } ?>
<td><?php print $winningpct; ?></td>
<?php if ($show_points) { ?>
<td><?php print $results['points']; ?></td>
<?php } ?>
</tr>
<?php
}
}
?>
</table>
<?php } ?>
<a name="pastscores"></a><h2>Past Scores</h2>
<form name="teamsort" method="post" action="<?php print $_SERVER['REQUEST_URI']; ?>#pastscores">
<p>
Show only
<select name="teamtosort">
<option value="all">All teams</option>
<?php
// Populate the list of teams
$queryteams = "SELECT sportsdb_teams.teamname, sportsdb_teams.teamid
FROM sportsdb_teams, sportsdb_divs
WHERE sportsdb_teams.teamdiv = sportsdb_divs.divid
AND sportsdb_divs.conference = $confid
ORDER BY teamname";
$resultteams=mysql_query($queryteams);
$numteams=mysql_num_rows($resultteams);
while ($teams = mysql_fetch_array($resultteams, MYSQL_ASSOC)) {
print "\t" . '<option value="' . $teams['teamid'] . '"';
if ($teams['teamid'] == $_POST['teamtosort']) {
print ' selected="selected"';
}
print '>' . $teams['teamname'] . "</option>\n";
}
?>
</select>
<input type="submit" value="Go" />
</p>
</form>
<table class="scorestable">
<tr>
<th>Date</th>
<th>Time</th>
<th>Home</th>
<th>Away</th>
<?php if ($show_fields) { ?>
<th>Field</th>
<?php } ?>
<th>Score</th>
<th> </th>
</tr>
<?php
$queryscores="SELECT sportsdb_wins.winid, sportsdb_wins.windate, sportsdb_wins.wintime, sportsdb_wins.rf, sportsdb_wins.ra, sportsdb_wins.winner,
sportsdb_wins.loser, sportsdb_wins.wincomments, sportsdb_wins.field, sportsdb_wins.winortie, sportsdb_teams2.teamname AS winningteam,
sportsdb_teams.teamname AS losingteam
FROM sportsdb_wins
LEFT JOIN sportsdb_teams ON sportsdb_wins.loser = sportsdb_teams.teamid
LEFT JOIN sportsdb_teams AS sportsdb_teams2 ON sportsdb_wins.winner = sportsdb_teams2.teamid
LEFT JOIN sportsdb_divs ON sportsdb_teams.teamdiv = sportsdb_divs.divid
LEFT JOIN sportsdb_divs AS sportsdb_divs2 ON sportsdb_teams2.teamdiv = sportsdb_divs2.divid
WHERE (sportsdb_divs.conference = $confid OR sportsdb_divs2.conference = $confid OR (sportsdb_wins.winconf = $confid AND (sportsdb_wins.loser = -1 OR sportsdb_wins.winner = -1))) AND sportsdb_wins.winortie != 3";
// Sort by team if specified
if (isset($_POST['teamtosort']) && $_POST['teamtosort'] != 'all') {
$teamtosort = intval($_POST['teamtosort']);
$queryscores .= " AND (sportsdb_wins.winner = $teamtosort OR sportsdb_wins.loser = $teamtosort)";
}
$queryscores .= ' ORDER BY wintime DESC';
$resultscores=mysql_query($queryscores);
$numscores=mysql_num_rows($resultscores);
while ($scores = mysql_fetch_array($resultscores, MYSQL_ASSOC)) {
$windateheader=$scores['windate'];
$windateformatted=date("F d, Y",$windateheader);
$wintime=$scores['wintime'];
$hour=date('g',$wintime);
$minute=date('i',$wintime);
$ampm=date('a',$wintime);
?>
<tr>
<td><?php print $windateformatted; ?></td>
<td><?php print $hour . ':' . $minute . $ampm; ?></td>
<td><?php print $scores['winningteam']; ?></td>
<td><?php print $scores['losingteam']; ?></td>
<?php if ($show_fields) { ?>
<td><?php print $scores['field']; ?></td>
<?php } ?>
<td><?php print $scores['rf'] . ' - ' . $scores['ra'];
if ($scores['winortie'] == 2 || $scores['winortie'] == 5) {
print ' (ff)';
}
print '</td>';
?>
<td><?php print $scores['wincomments']; ?></td>
</tr>
<?php } ?>
</table>
<a name="upcominggames"></a><h2>Upcoming Games</h2>
<form name="teamsort" method="post" action="<?php print $_SERVER['REQUEST_URI']; ?>#upcominggames">
<p>Show only
<select name="teamtosort">
<option value="all">All teams</option>
<?php
$queryteams = "SELECT sportsdb_teams.teamname, sportsdb_teams.teamid
FROM sportsdb_teams, sportsdb_divs
WHERE sportsdb_teams.teamdiv = sportsdb_divs.divid
AND sportsdb_divs.conference = $confid
ORDER BY teamname";
$resultteams=mysql_query($queryteams);
$numteams=mysql_num_rows($resultteams);
while ($teams = mysql_fetch_array($resultteams, MYSQL_ASSOC)) {
print "\t" . '<option value="' . $teams['teamid'] . '"';
if ($teams['teamid'] == $_POST['teamtosort']) {
print ' selected';
}
print '>' . $teams['teamname'] . "</option>\n";
}
?>
</select>
<input type="submit" value="Go" />
</p>
</form>
<table class="gamestable">
<tr>
<th>Date</th>
<th>Time</th>
<th>Home</th>
<th>Away</th>
<?php if ($show_fields) { ?>
<th>Field</th>
<?php } ?>
<th> </th>
</tr>
<?php
$queryscores = "SELECT sportsdb_wins.winid, sportsdb_wins.windate, sportsdb_wins.wintime, sportsdb_wins.winner, sportsdb_wins.loser,
sportsdb_wins.wincomments, sportsdb_wins.field, sportsdb_teams2.teamname AS winningteam, sportsdb_teams.teamname AS losingteam
FROM sportsdb_wins
LEFT JOIN sportsdb_teams ON sportsdb_wins.loser = sportsdb_teams.teamid
LEFT JOIN sportsdb_teams AS sportsdb_teams2 ON sportsdb_wins.winner = sportsdb_teams2.teamid
LEFT JOIN sportsdb_divs ON sportsdb_teams.teamdiv = sportsdb_divs.divid
LEFT JOIN sportsdb_divs AS sportsdb_divs2 ON sportsdb_teams2.teamdiv = sportsdb_divs2.divid
WHERE (sportsdb_divs.conference = $confid OR sportsdb_divs2.conference = $confid OR (sportsdb_wins.winconf = $confid AND (sportsdb_wins.loser = -1 OR sportsdb_wins.winner = -1))) AND sportsdb_wins.winortie = 3";
// Sort by team if specified
if (isset($_POST['teamtosort']) && $_POST['teamtosort'] != 'all') {
$teamtosort = intval($_POST['teamtosort']);
$queryscores .= " AND (sportsdb_wins.winner = $teamtosort OR sportsdb_wins.loser = $teamtosort)";
}
$queryscores .= ' ORDER BY wintime ASC';
$resultscores = mysql_query($queryscores);
$numscores = mysql_num_rows($resultscores);
while ($scores = mysql_fetch_array($resultscores, MYSQL_ASSOC)) {
$windateheader=$scores['windate'];
$windateformatted=date("F d, Y",$windateheader);
$wintime=$scores['wintime'];
$hour=date('g',$wintime);
$minute=date('i',$wintime);
$ampm=date('a',$wintime);
?>
<tr>
<td><?php print $windateformatted; ?></td>
<td><?php print $hour . ':' . $minute . $ampm; ?></td>
<td><?php print $scores['winningteam']; ?></td>
<td><?php print $scores['losingteam']; ?></td>
<?php if ($show_fields) { ?>
<td><?php print $scores['field']; ?></td>
<?php } ?>
<td><?php print $scores['wincomments'] ?></td>
</tr>
<?php
}
?>
</table>
<?php
}
}
// List the conference in a specified season
elseif (($show_season || isset($_GET['season'])) && !isset($_GET['seasons']) ) {
if (!$show_season || isset($_GET['season']) ) {
$show_season = intval($_GET['season']);
}
$query = 'SELECT seasonname FROM sportsdb_seasons WHERE seasonid = ' . $show_season . ' LIMIT 1';
$result = mysql_query($query) or die('Error in query ' . $query);
if (mysql_num_rows($result) == 0) {
die ('There is no such season.');
}
$seasonname = mysql_result($result,0);
$seasonname = htmlspecialchars($seasonname, ENT_QUOTES);
print '<p>Click here to view a list of seasons</p>' . "\n";
print '<h3>' . $seasonname . ' season</h3>' . "\n";
?>
<p>Click on a conference name to view its standings</p>
<?php
$query = "SELECT * FROM sportsdb_conferences WHERE season = $show_season ORDER BY conforder";
$result = mysql_query($query) or die('Error in query ' . $query);
$num = mysql_num_rows($result);
while ($confs = mysql_fetch_array($result, MYSQL_ASSOC)) {
print '<p>{$confs['confname']}</p>\n";
}
}
else {
?>
<p>Click on a season name to view its conferences</p>
<?php
// List the seasons
$query = 'SELECT * FROM sportsdb_seasons ORDER BY seasonorder';
$result = mysql_query($query) or die('Error in query ' . $query);
$num = mysql_num_rows($result);
while ($seasons = mysql_fetch_array($result, MYSQL_ASSOC)) {
$seasonname = htmlspecialchars($seasons['seasonname'], ENT_QUOTES);
print '<p>$seasonname</p>\n";
}
}
?>
</body>
</html>
Related
I'm building a forum for learning purposes. I'm trying without success to retrieve forum categories from the database and displaying them in a table, but only the first category displays in the table, the rest display outside the table. I will post my code, and a screenshot of the image.
<?php
include 'connect.php';
include 'header.php';
$sql = "SELECT categories.cat_id,categories.cat_name,
categories.cat_description, COUNT(topics.topic_id) AS topics
FROM categories
LEFT JOIN topics ON topics.topic_id = categories.cat_id
GROUP BY categories.cat_name, categories.cat_description,
categories.cat_id";
$result = mysql_query($sql);
if(!$result) {
echo 'The categories could not be displayed, please try again later.';
} else {
if(mysql_num_rows($result) == 0) {
echo 'No categories defined yet.';
} else {
//prepare the table
echo '
<div class="container">
<table class="table forum tale-striped table-hover">
<thead>
<tr>
<th class="cell-stat"></th>
<th><h3>Category</h3></th>
<th><h3>Last topic</h3></th>
</tr>
</thead>';
while($row = mysql_fetch_assoc($result)) {
echo '<tbody>';
echo '<tr >';
echo '<td class="text-center"><i class="fa fa-exclamation fa-2x text-danger"> </i></td>';
echo '<td><h3>' . $row['cat_name'] . '</h3>' . $row['cat_description'].'</td>';
echo '<td class="float-xs-right">';
//fetch last topic for each cat
$topicsql = "SELECT topic_id, topic_subject, topic_date, topic_cat
FROM topics
WHERE topic_cat = " . $row['cat_id'] . "
ORDER BY topic_date DESC
LIMIT 1";
$topicsresult = mysql_query($topicsql);
if(!$topicsresult) {
echo 'Last topic could not be displayed.';
} else {
if(mysql_num_rows($topicsresult) == 0) {
echo 'no topics';
} else {
while($topicrow = mysql_fetch_assoc($topicsresult))
echo '' . $topicrow['topic_subject'] . ' at ' . date('d-m-Y', strtotime($topicrow['topic_date']));
}
}
echo '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '</div>'; //container
}
}
}
include 'footer.php';
?>
https://www.dropbox.com/s/c1dgijuafgv9jzu/Capture.PNG?dl=0
Quite simply you have the closing </table> tag inside the while loop so once the first row is output you close the table. Just move it outside the while loop like this, also the opening <tbody> need moving above the while loop as well
<?php
include 'connect.php';
include 'header.php';
$sql = "SELECT categories.cat_id,categories.cat_name,
categories.cat_description, COUNT(topics.topic_id) AS topics
FROM categories
LEFT JOIN topics ON topics.topic_id = categories.cat_id
GROUP BY categories.cat_name, categories.cat_description,
categories.cat_id";
$result = mysql_query($sql);
if(!$result) {
echo 'The categories could not be displayed, please try again later.';
} else {
if(mysql_num_rows($result) == 0) {
echo 'No categories defined yet.';
} else {
//prepare the table
echo '
<div class="container">
<table class="table forum tale-striped table-hover">
<thead>
<tr>
<th class="cell-stat"></th>
<th><h3>Category</h3></th>
<th><h3>Last topic</h3></th>
</tr>
</thead>
<tbody>'; //<-- moved
while($row = mysql_fetch_assoc($result)) {
echo '<tr >';
echo '<td class="text-center"><i class="fa fa-exclamation fa-2x text-danger"> </i></td>';
echo '<td><h3>' . $row['cat_name'] . '</h3>' . $row['cat_description'].'</td>';
echo '<td class="float-xs-right">';
//fetch last topic for each cat
$topicsql = "SELECT topic_id, topic_subject, topic_date, topic_cat
FROM topics
WHERE topic_cat = " . $row['cat_id'] . "
ORDER BY topic_date DESC
LIMIT 1";
$topicsresult = mysql_query($topicsql);
if(!$topicsresult) {
echo 'Last topic could not be displayed.';
} else {
if(mysql_num_rows($topicsresult) == 0) {
echo 'no topics';
} else {
while($topicrow = mysql_fetch_assoc($topicsresult))
echo '' . $topicrow['topic_subject'] . ' at ' . date('d-m-Y', strtotime($topicrow['topic_date']));
}
}
echo '</td>';
echo '</tr>';
}
}
echo '</tbody>'; //<-- moved
echo '</table>'; //<-- moved
echo '</div>'; //container //<-- moved
}
include 'footer.php';
?>
Becuse you're closing the <table> tag within the while-loop. Also, the <tbody> should be outside the loop as well, since there should only be one <tbody> in a table like this.
i have the below code written, actually i thought of converting the current webpage to pdf document, but i couldnt make how to declare the current url and get the contents of the webpage in pdf doc. below is my code.
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
<?php
include "contractview.php?ID=129";
//This is your php page ?>
<?php
$html = ob_get_contents();
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
i have written include "contractview.php?ID=129"; but this was not working, can any one please help me in how to assign this to get the current page contents.
MPDF doesn't support includes. You have to put it in a var. The full html can be converted using jquery or in php with file_get_contents.
This is how i did it with full page.
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
<?php
//$content = file_get_contents("contractview.php?ID=129"); //<=== WRONG ONE
$content = file_get_contents("http://www.yourwebsite.com/contractview.php?ID=129"); //<=== getting content from url and not file!!
print($content);
//This is your php page ?>
<?php
$html = ob_get_contents($content); //<=== put content in ob
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
I see you are using ob_start and ob_end
You coudl also use
<?php
require("mpdf60/mpdf.php");
$mpdf=new mPDF('utf-8','Letter-L','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('{PAGENO}');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
$mpdf->debug = true;
// Buffer the following html with PHP so we can store it to a variable later
$content = file_get_contents("http://www.yourwebsite.com/contractview.php?ID=129"); //<=== getting content from url and not file!!
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($content);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>
<?php require_once ('header.php'); ?>
<!-- 10/15/2014 START: Freze table header row; Updated Fancybox so it works with jQuery 1.10.1 as well -->
<META content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" http-equiv="X-UA-Compatible">
<!--script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script duplicate 10/6/2015-->
<SCRIPT type="text/javascript" src="jQueryfloatThead/jquery.floatThead.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/site.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/bootstrap.js"></SCRIPT>
<SCRIPT type="text/javascript" src="jQueryfloatThead/less.js"></SCRIPT>
<!-- 10/15/2014 END -->
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border=0 cellpadding="0" cellspacing="0">
<tr><td height="36" background="images/topbar_bg.png" style="background-repeat:repeat-x;"><img src="images/topbar_bg.png" height="36"></td></tr>
<tr><td>
<table width="960" border=0 cellpadding="0" cellspacing="0" align="center">
<?php require_once ('topnav.php'); ?>
<tr><td>
<table width="100%" border=0 cellpadding="10" cellspacing="5">
<?php
if(!isset($_SESSION['Username'])) {
header('Location: home?errMsg=Your session has been expired. Please re-login again.');
}
?>
<tr><td bgcolor="#006ec7" valign="top" width="100%" class="headertd">FAR Compliance Portal</td></tr>
<tr><td bgcolor="#ebf4f9" valign="top" width="100%" height="300">
<?php
require_once ('dbconnection.php');
require_once ('contractcheck.php'); //Check if users can view this section
if (!isset($_REQUEST['ID'])) {
print "ERROR: No record has been selected.";
exit;
}
if (!is_numeric($_REQUEST['ID'])) {
print "ERROR: Invalid record has been selected.";
exit;
}
$thisID = $_REQUEST['ID'];
$sqlGet = "select * from far_contract where ID='" .$thisID. "'";
$resultGet = mysql_query($sqlGet, $dbconnection);
if (!$resultGet) {
echo 'Could not run query [1] ($thisID): ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($resultGet);
if ($num_rows==0 || $num_rows>1) {
print "Error: Invalid record is being called ($thisID). Please check with administrator.";
exit;
}
$row = mysql_fetch_array($resultGet);
$thisID = $row[0];
$thisContractNumber = $row[1];
$thisCustomer = $row[2];
$thisCeilingValue = $row[3];
//$thisEffectiveDate = $row[4];
//$thisExpirationDate = $row[5];
//$thisLegalEntity = $row[6];
$thisProjectName = $row[4];
$thisMFilesLink = $row[5];
$thisCreatedByID = $row[6];
$thisCreatedDate = $row[7];
$thisModifiedByID = $row[8];
$thisModifiedDate = $row[9];
$thisContractStatus = $row[10]; //12/22/2014
$thisNotes = $row[11]; //3/27/2015
$thisSubmittedByID = $row[17]; //10/1/2015
$thisSubmittedDate = $row[18]; //10/1/2015
$thisMasterAgreement = $row[19]; //10/6/2015
if ($thisContractStatus==NULL) $thisContractStatus="Not Submitted"; //12/22/2014
$thisSpecialStatusNotes = $row[15]; //4/15/2015
unset($resultGet);
//if ($thisEffectiveDate!="") $thisEffectiveDate = date("m/d/Y", strtotime($thisEffectiveDate));
//if ($thisExpirationDate!="") $thisExpirationDate = date("m/d/Y", strtotime($thisExpirationDate));
$sqlGetFAR = "select * from far_contract_clauses where ContractID='" .$thisID. "'";
$resultGet = mysql_query($sqlGetFAR, $dbconnection);
if (!$resultGet) {
echo 'Could not run query [2] ($thisID): ' . mysql_error();
exit;
}
$num_rows = mysql_num_rows($resultGet);
if ($num_rows>0) {
$thisSelectClause = "";
while ($row = mysql_fetch_array($resultGet)) {
if ($thisSelectClause=="")
$thisSelectClause = $row[2];
else
$thisSelectClause .= ",".$row[2];
}
}
unset($resultGet);
?>
<h1>Contract Records > View Record</h1>
<a href='php-to-pdf.php' target='_blank' ><input type='button' value='Convert to pdf'></a>
<table cellspacing=0 cellpadding=3 border=0 width="100%" class="table-bordered">
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>ID:</b></td>
<td class="resultTbl"><?php echo $thisID ?></td>
</tr>
<tr>
<td nowrap width="220" class="resultTbl" bgcolor='#d9e0e4'><b>Direct Customer's Solicitation/Contract Number:</b></td>
<td width="100%" class="resultTbl"><?php echo $thisContractNumber ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Direct Customer:</b></td>
<td class="resultTbl"><?php echo $thisCustomer ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Ceiling Value ($):</b></td>
<td class="resultTbl"><?php is_numeric($thisCeilingValue)? print "$ ".number_format($thisCeilingValue,2) : print ""; ?></td>
</tr>
<!--<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Effective Date:</b></td>
<td class="resultTbl"><//php echo $thisEffectiveDate //></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Expiration Date:</b></td>
<td class="resultTbl"><//php echo $thisExpirationDate //></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Rapiscan Legal Entity:</b></td>
<td class="resultTbl"><//php echo $thisLegalEntity //></td>
</tr>-->
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Project Name/Description:</b></td><?php //3/27/2015 ?>
<td class="resultTbl"><?php echo $thisProjectName ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>M-Files Link:</b></td>
<td class="resultTbl"><?php echo $thisMFilesLink ?></td>
</tr>
<tr><?php //3/27/2015 ?>
<td class="resultTbl" bgcolor='#d9e0e4' valign='top'><b>Notes:</b></td>
<td class="resultTbl"><?php echo $thisNotes ?></td>
</tr>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Created By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisCreatedByID) . " on " . $thisCreatedDate ?></td>
</tr>
<?php
$SubmissionDate = $thisCreatedDate; //1/6/2015
if ($thisModifiedByID!="") { ?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Last Modified By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisModifiedByID) . " on " . $thisModifiedDate ?></td>
</tr>
<?php
$SubmissionDate = $thisModifiedDate; //1/6/2015
}
?>
<?php
$SubmittedDate = $thisSubmittedDate; //10/1/2015 Added Submitted By and Submitted Date
if ($thisSubmittedByID!="") { ?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Submitted By:</b></td>
<td class="resultTbl"><?php echo fetchFullName($thisSubmittedByID) . " on " . $thisSubmittedDate ?></td>
</tr>
<?php
$SubmittedDate = $thisSubmittedDate; //10/1/2015
}
?>
<?php
$MasterAgreement = $thisMasterAgreement; //10/1/2015 Added Submitted By and Submitted Date
?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Master/Framework<b>Agreement Contract</b></td>
<td class="resultTbl"><?php echo ($thisMasterAgreement==1)?'Yes':'No'; ?></td>
</tr>
<?php
?>
<tr>
<td class="resultTbl" bgcolor='#d9e0e4'><b>Status:</b></td>
<td class="resultTbl"><?php echo $thisContractStatus //12/22/2014 ?>
<?php //4/15/2015
if ($AllowContractFull) {
if ($thisContractStatus=="Submitted") {
print " ";
print "[Suspend]";
print " [Cancel]";
} elseif ($thisContractStatus=="Suspended") {
print " ";
print "[Re-activate]";
print " [Cancel]";
}
}
if (! ($thisSpecialStatusNotes=="" || is_null($thisSpecialStatusNotes)) ) {
print "<BR><font color=gray>$thisSpecialStatusNotes</font>";
}
?>
</td>
</tr>
<tr><td valign=top colspan=2 class="resultTbl"><b>FAR Clauses:</b></td></tr>
<tr><td valign=top colspan=2 class="resultTbl">
<?php
//get list of departments
$sql = "select * from far_departments order by Department";
$result = mysql_query($sql, $dbconnection);
if (!$result) {
echo 'Could not run query [3]: ' . mysql_error();
exit;
}
$deptList = array();
while ($row = mysql_fetch_array($result)) { //loop each department
$deptList[] = $row[1];
}
unset ($result);
printByCompliance ($thisID, $thisSelectClause, $thisContractStatus, $SubmissionDate); //1/6/2015
?>
</td>
</tr>
</table>
<?php
require_once ('logging.php'); //7/31/2014
mysql_close($dbconnection);
?>
</td></tr>
</table>
</td></tr>
<?php require_once ('footer.php'); ?>
</table>
</td></tr>
</table>
</body>
</html>
<?php
function printByCompliance ($thisID, $thisSelectClause, $thisContractStatus, $SubmissionDate){ //1/6/2015
global $deptList;
global $dbconnection;
//print table header
//echo "<h1>Compliance Report</h1>";
echo "<DIV id='options'><table width='100%' class='table table-bordered table-striped' cellspacing=0 cellpadding=5>";
echo "<thead><tr bgcolor='#d9e0e4'>";
echo "<th class='resultTbl' nowrap><b>FAR Clauses</b><img src='images/spacer.gif' width='80' height='1'></th>"; //9/15/2014
if ($thisContractStatus=="Submitted" || $thisContractStatus=="Suspended" || $thisContractStatus=="Cancelled") //4/15/2015
echo "<th class='resultTbl' nowrap><font color=blue><b>Certified<BR>as of<BR>".str_replace(" ", "<BR>", $SubmissionDate)."?</b></font></th>"; //1/6/2015
else
echo "<th class='resultTbl' nowrap><font color=blue><b>Certified?</b></font></th>"; //9/15/2014
foreach ($deptList as $EachDept) { //loop each dept
echo "<th class='resultTbl' align=center><b>" . $EachDept . "</b></th>";
}
echo "</tr></thead>"; //10/15/2014 END
//get all questions
$sql = "select * from far_questions where QStatus='ACTIVE' and ID in ($thisSelectClause) order by Title, Alternate"; //2/9/2015
$result = mysql_query($sql, $dbconnection);
if (!$result) {
echo 'Could not run query [4]: ' . mysql_error();
exit;
}
$listQuestionArray = array(); //START natural-order sorting questions by title
while ($row = mysql_fetch_array($result)) {
$listQuestionArray[] = array($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7]); //2/9/2015; 10/10/2014; 6/17/2014
}
usort($listQuestionArray, function ($elem1, $elem2) {
return strnatcmp ($elem1['1']." ".$elem1['7'], $elem2['1']." ".$elem2['7']);
//2/9/2015 need to take Alternate in nartural sort*** return strnatcmp ($elem1['1'], $elem2['1']);
});
unset($row); //END natural-order sorting questions by title
foreach ($listQuestionArray as $row) { //loop each question
$thisQuestionID = $row[0];
$thisTitle = trim($row[1]);
$thisURL = trim($row[2]);
$thisVersionDate = trim($row[3]);
$thisFrequency = trim($row[4]); //6/17/2014
$thisClauseType = trim($row[6]); //10/10/2014
$thisAlternate = trim($row[7]); //2/9/2015
$RequireDepartment = ""; //6/17/2014 START new tbl structure
if ($thisClauseType=="YELLOW") { //10/10/2014
$sqlgetdept = "select RequireDepartment from far_yellowDept where QuestionID='$thisQuestionID'";
} else {
$sqlgetdept = "select RequireDepartment from far_questionsDept where QuestionID='$thisQuestionID'";
} //10/10/2014
$resultgd = mysql_query($sqlgetdept, $dbconnection);
if (!$resultgd) {
echo 'Could not run query [6]: ' . mysql_error();
exit;
}
while ($rowgd = mysql_fetch_array($resultgd)) {
$RequireDepartment .= $rowgd[0] . ", ";
}
unset ($rowgd);
unset ($resultgd);
//$RequireDepartment = trim($row[5]);
//$thisFrequency = trim($row[6]); //6/17/2014 END
$curClauseInfo = ""; //9/15/2014 temp string for Clause info
$curClauseInfo .= "<td class=resultTbl bgcolor=#d9e0e4><a class='rptnav' href='" .$thisURL. "' target=new>" . $thisTitle . "</a>";
if ($thisVersionDate!="" && $thisVersionDate != NULL) {
$curClauseInfo .= "<BR>(" .$thisVersionDate. ")";
}
if ($thisAlternate!="" && $thisAlternate != NULL) { //2/9/2015
$curClauseInfo .= "<BR><BR>" .$thisAlternate;
}
$curStatusStr = ""; //9/15/2014 temp string to store current status for each dept for current FARS clause
$chkQuestion = true; //assume this question is compliance.
foreach ($deptList as $EachDept) { //loop each dept
if (strpos($RequireDepartment, $EachDept) !== false) { //if this question is required for current dept
$curStatusStr .= "<td class=resultTbl nowrap align=center>";
if ($thisClauseType=="YELLOW") { //10/10/2014
//12/11/2014 fetch approval status for YELLOW clause from new table
$sqlConApp = "select * from far_contract_approval where ContractID='$thisID' and QuestionID='$thisQuestionID' and Department='{$EachDept}'";
$resultConApp = mysql_query($sqlConApp, $dbconnection);
if (!$resultConApp) {
echo 'Could not run query [7]: ' . mysql_error();
exit;
}
$num_rowsConApp = mysql_num_rows($resultConApp);
if ($num_rowsConApp>0) { //if approval response is found
$rowConApp = mysql_fetch_array($resultConApp);
$curStatusStr .= "<B>Approved By</B><BR>" . fetchFullName($rowConApp[4]) . "<BR>" . str_replace(" ", "<BR>", $rowConApp[5]);
} else { //if NO approval response is found
$curStatusStr .= "Approval<BR>Required";
}
unset($resultConApp); //12/11/2014
$curStatusStr .= "</td>";
$chkQuestion=false;
} else { //10/10/2014 for clause type = CERTIFY and GREEN
//check for approval
$sqlConApp = "select * from far_contract_approval where ContractID='$thisID' and QuestionID='$thisQuestionID' and Department='{$EachDept}'";
$resultConApp = mysql_query($sqlConApp, $dbconnection);
if (!$resultConApp) {
echo 'Could not run query [7b]: ' . mysql_error();
exit;
}
$num_rowsConApp = mysql_num_rows($resultConApp);
if ($num_rowsConApp>0) { //if approval response is found
$rowConApp = mysql_fetch_array($resultConApp);
$curStatusStr .= "<B>Approved By</B><BR>" . fetchFullName($rowConApp[4]) . "<BR>" . str_replace(" ", "<BR>", $rowConApp[5]);
} else {
//get latest response per each question
$sql2 = "select * from far_responses where QuestionID=$thisQuestionID and Department='{$EachDept}' order by ResponseDate desc limit 1";
$result2 = mysql_query($sql2, $dbconnection);
if (!$result2) {
echo 'Could not run query [8]: ' . mysql_error();
exit;
}
$num_rows2 = mysql_num_rows($result2);
if ($num_rows2>0) { //if response is found
$row2 = mysql_fetch_array($result2);
$thisResponse = $row2[2];
$thisResponseBy = $row2[5];
$thisResponseDate = $row2[6];
$tempResponseDate = str_replace(" ", "<BR>", $thisResponseDate); //6/12/2014 show time on next line
$curStatusStr .= "<B>". $thisResponse . "</B><BR>" . $thisResponseBy . "<BR>" . $tempResponseDate;
if ($thisResponse=="YES") { //if latest response is YES, check if it has expired or not
/* 6/2/2014 Disable this function - no need to check Frequency as all answers will be reset on 1/1
$chkDate = strtotime($thisResponseDate);
$chkDate = strtotime("+$thisFrequency day", $chkDate);
if (time() > $chkDate) {
print "<font color=red><BR>Expired</font>";
$chkQuestion=false;
}
6/2/2014 */
} else { //PENDING or EXPIRED
$chkQuestion=false;
}
} else { //no previous submission
$curStatusStr .= "Response<BR>Pending";
$chkQuestion=false;
}
}
unset($resultConApp); //12/11/2014
$curStatusStr .= "</td>";
} //10/10/2014
} else { //this question does not apply to current dept
$curStatusStr .= "<td class=resultTbl align=center>N/A</td>";
}
}
$curStatusBox = ""; //9/15/2014 temp string to store green/red icon
$curStatusBox .= "<td class=resultTbl align=center bgcolor=#d9f1fe>";
if ($thisContractStatus=="Submitted" || $thisContractStatus=="Suspended" || $thisContractStatus=="Cancelled") { //4/15/2015; 1/6/2015 Contract has been submitted
$sqlFreezeStat = "select LightIndicator from far_contract_clauses where ContractID='$thisID' and QuestionID='$thisQuestionID'";
$resultFreezeStat = mysql_query($sqlFreezeStat, $dbconnection);
if (!$resultFreezeStat) {
echo 'Could not run query [10]: ' . mysql_error();
exit;
}
$num_rowsFS = mysql_num_rows($resultFreezeStat);
if ($num_rowsFS>0) { //if response is found
$rowFS = mysql_fetch_array($resultFreezeStat);
switch ($rowFS[0]) {
case "GREEN": $curStatusBox .= "<img src='images/greenicon.gif' width='20'>"; break;
case "YELLOW": $curStatusBox .= "<img src='images/yellowicon.gif' width='20'>"; break;
case "RED": $curStatusBox .= "<img src='images/redicon.gif' width='20'>"; break;
default: $curStatusBox .= "Status is not being frozen for this record";
}
} else { $curStatusBox .= "Status is not being frozen for this record"; }
unset ($resultFreezeStat);
} else { //1/6/2015: Not submitted - so shows real-time light status
if ((int)$chkQuestion==1) {
$curStatusBox .= "<img src='images/greenicon.gif' width='20'>";
//9/15/2014 Latest Audit Info
/* 12/11/2014 hide audit *** (if want to add it back, need to add fancybox script ***
$sqlchkAudit = "select AuditDate from far_audit where QuestionID=$thisQuestionID order by AuditDate Desc limit 1";
$resultA = mysql_query($sqlchkAudit, $dbconnection);
if (!$resultA) {
echo 'Could not run query [9]: ' . mysql_error();
exit;
}
$num_rowsA = mysql_num_rows($resultA);
if ($num_rowsA >0) { //if response is found
$rowA = mysql_fetch_array($resultA);
$AuditDateTemp = $rowA[0];
$AuditDateSplit = explode(" ", $AuditDateTemp);
$AuditDate = "<a class=\"fancybox\" href=\"audithistory.php?ID=" .$thisQuestionID. "\">" .$AuditDateSplit[0]. "</a>";
//$AuditDate = $AuditDateSplit[0];
} else {
$AuditDate = "N/A";
}
$curClauseInfo .= "<BR><BR>Last Audit: " . $AuditDate;
if($_SESSION['UserAccessLevel']=="FULLAUDIT") //9/15/2014 new access level AUDIT rights
$curClauseInfo .= "<BR>Auditor: <a class=\"fancybox\" href=\"audit.php?ID=" .$thisQuestionID. "\">Audit It</a></td>";
else
$curClauseInfo .= "</td>";
hide audit*** */
} elseif ($thisClauseType=="YELLOW") { //10/10/2014
$curStatusBox .= "<img src='images/yellowicon.gif' width='20'>";
$curClauseInfo .= "</td>";
} else {
$curStatusBox .= "<img src='images/redicon.gif' width='20'>";
$curClauseInfo .= "</td>";
}
}
$curStatusBox .= "</td>";
print "<tr>"; //9/15/2014 Print out new temp strings
print $curClauseInfo;
print $curStatusBox;
print $curStatusStr;
print "</tr>";
}
echo "</table></div>"; //10/15/2014 closing DIV, added document ready
?>
<SCRIPT type="text/javascript">
$(document).ready(function () {
$('#options table').floatThead({
//the pageTop is a global function i have here, it takes care of making the table float under my floated nav
scrollingTop: pageTop,
useAbsolutePositioning: false
});
});
</SCRIPT> <!--10/15/2014 END -->
<?php
}
?>
It's smaller and cleaner and the file_get_contents() can get the job done. But you always need to make sure you have the html of the page.
This is my order list sortOrder.php:
<?php
$queryMain ="SELECT newsvid.id, newsvid.addName, newsvid.vidTitle, newsvid.vidType, newsvid.size, newsvid.url, newsvid.vidSD, newsvid.published, videoinformation.vidLD, videoinformation.vidYear, videoinformation.vidCity, videoinformation.vidZanr, videoinformation.vidZanr2, videoinformation.vidZanr3, videoinformation.vidQuality, videoinformation.vidTranslated, videoinformation.vidTime FROM newsvid, videoinformation WHERE newsvid.id = videoinformation.id AND approved='1'";
// Video type
$vType = isset($_GET['vType']) ? $_GET['vType'] : 'ALL';
$goodTypeParam = array("AnyType", "Film", "Serials", "Cartoon", "Anime");
if (in_array($vType, $goodTypeParam)) {
if($vType == 'AnyType'){}
else{$queryMain .= " AND newsvid.vidType ='".$_GET['vType']."'";}
}
//Video Genre one
$vGenre = isset($_GET['vGenre']) ? $_GET['vGenre'] : 'ALL';
$goodGenreParam = array("AnyGenre1", "Action", "Adventure", "Comedy", "Crime", "Faction", "Fantasy", "Historical", "Horror", "Mystery", "Paranoid", "Philosophical", "Political", "Realistic", "Romance", "Saga", "Satire", "Science-Fiction", "Slice-Of-Life", "Speculative", "Anime");
if (in_array($vGenre, $goodGenreParam)) {
if($vGenre == 'AnyGenre1'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre']."')";}
}
//Video Genre two
$vGenre2 = isset($_GET['vGenre2']) ? $_GET['vGenre2'] : 'ALL';
$goodGenre2Param = array("AnyGenre2", "Action2", "Adventure2", "Comedy2", "Crime2", "Faction2", "Fantasy2", "Historical2", "Horror2", "Mystery2", "Paranoid2", "Philosophical2", "Political2", "Realistic2", "Romance2", "Saga2", "Satire2", "Science-Fiction2", "Slice-Of-Life2", "Speculative2", "Anime2");
if (in_array(vGenre2, $goodGenre2Param)) {
if(vGenre2 == 'AnyGenre2'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre2']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre2']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre2']."')";}
}
//Video Genre three
$vGenre3 = isset($_GET['vGenre3']) ? $_GET['vGenre3'] : 'ALL';
$goodGenre3Param = array("AnyGenre3", "Action", "Adventure", "Comedy", "Crime", "Faction", "Fantasy", "Historical", "Horror", "Mystery", "Paranoid", "Philosophical", "Political", "Realistic", "Romance", "Saga", "Satire", "Science-Fiction", "Slice-Of-Life", "Speculative", "Anime");
if (in_array($vGenre, $goodGenre3Param)) {
if($vGenre3 == 'AnyGenre3'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre3']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre3']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre3']."')";}
}
// Video Years
$vYear = isset($_GET['vYear']) ? $_GET['vYear'] : 'ALL';
$goodYearParam = array("AnyYear", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998", "1997");
if (in_array($vType, $goodYearParam)) {
if($vYear == 'AnyYear'){}
else{$queryMain .= " AND newsvid.vidYear ='".$_GET['vYear']."'";}
}
// Video City
$vCity = isset($_GET['vCity']) ? $_GET['vCity'] : 'ALL';
$goodCityParam = array("AnyCity", "Russian", "England");
if (in_array($vCity, $goodCityParam)) {
if($vCity == 'AnyCity'){}
else{$queryMain .= " AND newsvid.vidCity ='".$_GET['vCity']."'";}
}
//NEW of OLD
$order = isset($_GET['order']) ? $_GET['order'] : 'ALL';
$goodParam = array("NEW", "OLD");
if (in_array($order, $goodParam)) {
if($order == 'NEW'){
$queryMain .= " ORDER BY newsvid.id ASC";
}else if($order == 'OLD'){
$queryMain .= " ORDER BY newsvid.id DESC";
}else{
$queryMain .= " AND videoinformation.vidYear = 2014";
}
}
?>
And this is main page view.php:
<!DOCTYPE lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<?php include 'BSH.php' ?>
<link rel="stylesheet" type="text/css" href="CSS/sdvid.css">
<title><?php echo $lang['PAGE_TITLE_MAIN'] ?></title>
</head>
<body>
<?php
include_once 'userPages/check_login_status.php';
include_once 'incIndex/headerTop.php';
include 'connect/con.php';
include_once 'inc/sortOrder.php';
?>
<?php
$sqlPages = "SELECT COUNT(id) FROM newsvid WHERE approved='1'";
$queryPages = mysqli_query($con, $sqlPages);
$row = mysqli_fetch_row($queryPages);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 1;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = "LIMIT " .($pagenum - 1) * $page_rows ."," .$page_rows;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$queryMainList = $queryMain . $limit;
$resultDisplay = mysqli_query($con, $queryMainList);
// This shows the user what page they are on, and the total number of pages
$pagesTitle = "On website <b>$rows</b>";
$pagesOutOf = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($resultDisplay, MYSQLI_ASSOC)){
$list .= "<div class=\"panel-heading\">
<div><a class=\"panel-title btn-block\" href=\"details.php?id=".$row['id']."\"><h3>".$row['id']." | ".$row['vidTitle']."</h3></a></div>
</div>
<div class=\"panel-body\">
<div class=\"imgCover\"><img class=\"imageCover\"src=\"" . $row['url'] . "\"></div>
<div class=\"vidSD\">" . $row['vidSD'] . "</div>
<div class=\"vidDetails\">
<hr class=\"style-two\">
<table>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtYear'] . "</strong></td><td class=\"vidDetailsTD\">" . $row['vidYear'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtCity'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidCity'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtGenre'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidZanr'] ." , ". $row['vidZanr2'] ." , ". $row['vidZanr3'] . "</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtQuality'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidQuality'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtTranslatedBy'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidTranslated'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtVideoTime'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidTime'] . "</td></tr>
</table>
</div></div>
<div class=\"panel-footer\">
<h6><strong>" . $lang['vsdAuthor'] . "</strong>".$row['addName']."</h6>
<div><h6><strong>" . $lang['vsdPublished'] . "</strong>" . $row['published'] . "</h6></div>
</div>";
}
mysqli_close($con);
?>
<div class="mainLeftCover">
<form action="view.php" method="GET">
<div class="input-group" style="width:180px">
<span class="input-group-addon" style="width:65px"><?php echo $lang['vidOrderTitleNew'] ?></span>
<select class="form-control" name = "order">
<option value="NEW">NEW</option>
<option value="OLD">OLD</option>
</select>
</div>
<?php
include_once 'inc/sortInc/sortType.php';
include_once 'inc/sortInc/sortGenre.php';
include_once 'inc/sortInc/sortGenre2.php';
include_once 'inc/sortInc/sortGenre3.php';
include_once 'inc/sortInc/sortYear.php';
include_once 'inc/sortInc/sortCity.php';
?>
<br><button type="submit" class="btn btn-default" style="width:180px">Submit</button>
</form>
<?php echo" <div id=\"pagination_controls\">" .$paginationCtrls. "</div>"; ?>
</div>
<?php
echo "<div class=\"maincover \" data-role=\"scrollbox\" data-scroll=\"vertical\">";
echo "<div class=\"panel panel-default\">";
echo" <div style=\"background-color:#fff\">" .$list. "</div>";
echo "</div></div>";
?>
Just for encase I gave full code. The problem is, that PAGINATION on it's own working fine... And ORDER function working fine separately as well. BUT TOGETHER they do not want to work. As result I have working pagination and if try to use sort it's just become empty page.
What I need..is somehow make sorting method working with pagination together, but i'm stuck how to do it.
I have this url when I'm using pagination:
http://example.net/view.php?pn=3
And this one when I'm using order:
http://example.net/view.php?order=NEW&vType=Film&vGenre=AnyGenre1&vGenre2=AnyGenre2&vGenre3=AnyGenre3&vYear=AnyYear&vCity=AnyCity
AND I need that URL will be like this:
http://example.net/view.php?pn=3&order=NEW&vType=Film&vGenre=AnyGenre1&vGenre2=AnyGenre2&vGenre3=AnyGenre3&vYear=AnyYear&vCity=AnyCity
That if you sort the page... it will remember how user was sort the list and open pages (pn=1, pn=2) will change.
May be some how save sort result and then use it in pagination..need to save it maybe when submit button pressed? But how can I save result from user???
<?php
session_start();
include_once 'dbconnect.php';
?>
<?php include ('head.php') ; ?>
<?php include ('menu.php') ; ?>
<?php if (isset($_SESSION['usr_id'])) { ?>
<?
$per_page = 15;
if (isset($_GET["page"])) {$page = $_GET["page"];}else {$page = 1;}
if (isset($_GET["order"])) {$order = $_GET["order"];}else {$order = username;}
$start_from = ($page-1) * $per_page;
if(isset($_GET['order']) && $_GET['order'] == 'user_id'){
$query = "select * from users order by user_id DESC limit $start_from, $per_page";}
if(isset($_GET['order']) && $_GET['order'] == 'username'){
$query = "select * from users order by username ASC limit $start_from, $per_page";}
if(isset($_GET['order']) && $_GET['order'] == 'posts'){
$query = "select * from users order by posts DESC limit $start_from, $per_page";}
$result = mysqli_query ($DBcon, $query);
$user_list_result = $DBcon->query("select * from users order by $order ASC limit 100");
$session = $_SESSION['usr_name'];
$query = $DBcon->query("SELECT * FROM users WHERE username='$session'");
$userRow=$query->fetch_array();
if ($userRow['userlevel'] > 0) {
?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-12">
<div class="panel panel-default panel-compact panel-wallet">
<div class="panel-body">
<center><h1>Userlist </h1></center>
<center>
<table >
<tr> <td width="20%"><b>ID </b></td>
<td width="20%"><b>Nickname </b></td>
<td width="20%"><b>Posts </b></td>
<td width="20%"><b>Message </b></td>
<td width="20%"><b>Click </b></td> </tr>
<?php
while($UserlistRow = $result->fetch_array())
{
echo "
<tr>
<td>$UserlistRow[user_id]</td>
<td><a href=user_profile.php?user=$UserlistRow[username]>$UserlistRow[username]</a></td>
<td>$UserlistRow[posts]</td>
</center>
<td><a href=msg_send.php?to=$UserlistRow[username]>Send Message</a></td>
<td><a href=user_click.php?to=$UserlistRow[username]>Click</a></td> ";?>
</tr>
<?php } ?> </table>
</center>
<?
$query = "select * from users order by $order";
$result = mysqli_query($DBcon, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='user_list.php?page=" . ($_GET['page']+1) . "&order=" . ($_GET['order']) . "'>Next Page</a>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='user_list.php?page=".$i."&order=" . ($_GET['order']) . "'>".$i."</a> ";
};
echo "<a href='user_list.php?page=" . ($_GET['page']-1) . "&order=" . ($_GET['order']) . "'>Previous Page</a>";
?>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<?php } else { include('login_frame.php'); } ?>
<?php include ('footer.php') ; ?>
I need some help on how to echo out my mysql data into a html table. I'm trying to put in the relevant table tags where necessary but I must be doing it wrong as its not looking how I want it.
Here's what I am getting:
ID Name Number Note Alert
1
2
Nick Nick insurance insurance alert alert
Here is how I want it to look:
ID Name Number Note Alert
1 Nick Insurance Alert
2 Nick Insurance Alert
Here is my code, can someone please show me where I need to put my table tags to get the desired result:
<?php
include 'config.php';
$data = mysql_query("SELECT * FROM supplier_stats") or die(mysql_error());
echo "<table class=\"table\" style=\"width:900px; font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px; color:#96969;\" >";
while ($info = mysql_fetch_array($data))
{
echo "<tr><td><p>" . $info['id'] . "</p></td></tr>";
}
?>
<?php
include 'config.php';
$data = mysql_query("SELECT * FROM supplier_stats") or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
echo "<td><p>" . $info['company_name'] . "</p></td>";
}
?>
<?php
include 'config.php';
$data = mysql_query("SELECT TIMESTAMPDIFF(DAY, insurance_date, NOW()) AS expire_date
FROM supplier_stats") or die(mysql_error()); ?>
<?php
include 'config.php';
$result = mysql_query("SELECT TIMESTAMPDIFF(DAY, insurance_date, NOW()) AS expire_date
FROM supplier_stats") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$days = $row['expire_date'] - 1;
if ($days > 0)
{
echo "<td><p>Insurance expires in <font color=\"red\">{$row['expire_date']} day(s)!</font></p></td>";
}
else
{
$when = $days * -1;
echo "<td><p>Insurance expires";
if ($when > 1)
{
echo " in {$when} days</p></td>";
}
if ($when >= 8)
{
echo " <div class=\"green_light\"></div>";
}
if ($when <= 7)
{
echo " <div class=\"red_light\"></div>";
}
elseif ($when === 1)
{
echo " tomorrow</p></td>";
}
elseif ($when = 0)
{
echo " today</p></td>";
}
}
}
?>
<?php
include 'config.php';
$result = mysql_query("SELECT TIMESTAMPDIFF(DAY, insurance_date, NOW()) AS expire_date
FROM supplier_stats") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$days = $row['expire_date'] - 1;
if ($days > 8)
{
echo "a is bigger than b";
}
}
echo "</table>"; //Close the table in HTML
?>
You need more or less somethin like this:
<?php include 'config.php';
$data = mysql_query("SELECT *, TIMESTAMPDIFF(DAY, insurance_date, NOW()) AS expire_date FROM supplier_stats")
or die(mysql_error());
echo "<table class=\"table\" style=\"width:900px; font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px; color:#96969;\" >";
while($row = mysql_fetch_array( $data )) {
$days = $row['expire_date'] -1;
echo "<tr><td><p>".$row['id'] . "</p></td>";
echo "<td><p>".$row['company_name'] . "</p></td>";
if ($days > 0) {
echo "<td><p>Insurance expires in <font color=\"red\">{$row['expire_date']} day(s)!</font></p></td>";
} else {
$when = $days*-1;
echo "<td><p>Insurance expires";
if ($when > 1){
echo " in {$when} days</p></td>";
}
if ($when >= 8){
echo " <div class=\"green_light\"></div>";
}
if ($when <= 7){
echo " <div class=\"red_light\"></div>";
} elseif ($when ===1) {
echo " tomorrow</p></td>";
} elseif ($when == 0) {
echo " today</p></td>";
}
}
echo "<tr>";
}
echo "</table>"; //Close the table in HTML
?>
you've closed after first that is why you are getting output like this..remove from:
echo "<tr><td><p>".$info['id'] . "</p></td></tr>";
above line...and close after while loop ends..
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Number</td>
<td>Note</td>
<td>Alert</td>
</tr>
<?php
$sql = mysql_query("your query");
$i = 0;
while ($info = mysql_fetch_array($data))
{
$i++
?>
<td><?php echo $i; ?></td>
<td><?php echo $info['name']; ?></td>
<td><?php echo $info['number']; ?></td>
<td><?php echo $info['note']; ?></td>
<td><?php echo $info['alert']; ?></td>
</tr>
<?php
}
?>
</table>
Currently I've 2 tables and have the datas are dynamic.
I need to add pagination for both tables seperately. I had added paginator using paginator class and it is working fine. But the problem is when I click on the next button of the first table then the contents of both tables are changed in to the next page.
Paginator.php
<?php
// Paginator Class
// error_reporting(E_ALL);
define("QS_VAR", "page"); // the variable name inside the query string (don't use this name inside other links)
define("STR_FWD", "Next>>"); // the string is used for a link (step forward)
define("STR_BWD", "<<Prev"); // the string is used for a link (step backward)
$scriptname = (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '');
define("SCRIPT_NAME", $scriptname);
$v = (isset($_REQUEST['page_num_rows']) ? (is_numeric($_REQUEST['page_num_rows']) ? $_REQUEST['page_num_rows'] : 5) : 5);
define("NUM_ROWS", $v); // the number of records on each page
class Paginator {
var $sql;
var $result;
var $get_var = QS_VAR;
var $rows_on_page = NUM_ROWS;
var $str_forward = STR_FWD;
var $str_backward = STR_BWD;
var $all_rows;
var $num_rows;
var $page;
var $number_pages;
var $url_name = SCRIPT_NAME;
// constructor
function Paginator() {
}
// sets the current page number
function set_page() {
$this->page = (isset($_REQUEST[$this->get_var]) && $_REQUEST[$this->get_var] != "") ? $_REQUEST[$this->get_var] : 0;
return $this->page;
}
// gets the total number of records
function get_total_rows() {
$tmp_result = mysql_query($this->sql);
$this->all_rows = mysql_num_rows($tmp_result);
mysql_free_result($tmp_result);
return $this->all_rows;
}
// get the totale number of result pages
function get_num_pages() {
$this->number_pages = ceil($this->get_total_rows() / $this->rows_on_page);
return $this->number_pages;
}
// returns the records for the current page
function get_page_result() {
$start = $this->set_page() * $this->rows_on_page;
$page_sql = sprintf("%s LIMIT %s, %s", $this->sql, $start, $this->rows_on_page);
$this->result = mysql_query($page_sql);
return $this->result;
}
// get the number of rows on the current page
function get_page_num_rows() {
$this->num_rows = #mysql_num_rows($this->result);
return $this->num_rows;
}
// free the database result
function free_page_result() {
#mysql_free_result($this->result);
}
function display_row_count() {
$var = $this->get_var;
$url_part1 = $this->url_name . "?";
$url_part2 = "&" . $var . "=0" . $this->rebuild_qs($var);
$select = " Show ";
$select.="<form method=get name=page_num_rows_form action=\"$this->url_name\" >"; // [form used for javascript disabled case] -not working
$select.="<select name=page_num_rows id=page_num_rows onChange=\"window.location='$url_part1'+'page_num_rows='+this.value+'$url_part2'\" >";
$select.="<option value=50 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 50 ? ' selected ' : '') : '') . " >50</option>";
$select.="<option value=100 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 100 ? ' selected ' : '') : '') . " >100</option>";
$select.="<option value=150 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 150 ? ' selected ' : '') : '') . " >150</option>";
$select.="<option value=200 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 200 ? ' selected ' : '') : '') . " >200</option>";
$select.="<option value=500 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 500 ? ' selected ' : '') : '') . " >500</option>";
$select.="</select>";
$select.="<noscript> <input type=submit value=Go /></noscript>";
$select.="</form>"; // form used for javascript disabled case -- not working
$select.=" per page";
return $select;
}
// function to handle other querystring than the page variable
function rebuild_qs($curr_var) {
if (!empty($_SERVER['QUERY_STRING'])) {
$parts = explode("&", $_SERVER['QUERY_STRING']);
$newParts = array();
foreach ($parts as $val) {
if (stristr($val, $curr_var) == false) {
array_push($newParts, $val);
}
}
if (count($newParts) != 0) {
$qs = "&" . implode("&", $newParts);
} else {
return false;
}
return $qs; // this is your new created query string
} else {
return false;
}
}
// this method will return the navigation links for the conplete recordset
function navigation($separator = " | ", $css_current = "", $back_forward = false) {
$max_links = NUM_LINKS;
$curr_pages = $this->set_page();
$all_pages = $this->get_num_pages() - 1;
$var = $this->get_var;
$navi_string = "";
if (!$back_forward) {
$max_links = ($max_links < 2) ? 2 : $max_links;
}
if ($curr_pages <= $all_pages && $curr_pages >= 0) {
if ($curr_pages > ceil($max_links / 2)) {
$start = ($curr_pages - ceil($max_links / 2) > 0) ? $curr_pages - ceil($max_links / 2) : 1;
$end = $curr_pages + ceil($max_links / 2);
if ($end >= $all_pages) {
$end = $all_pages + 1;
$start = ($all_pages - ($max_links - 1) > 0) ? $all_pages - ($max_links - 1) : 1;
}
} else {
$start = 0;
$end = ($all_pages >= $max_links) ? $max_links : $all_pages + 1;
}
if ($all_pages >= 1) {
$forward = $curr_pages + 1;
$backward = $curr_pages - 1;
$navi_string = ($curr_pages > 0) ? "" . $this->str_first . " " . $this->str_backward . " " : $this->str_first . " " . $this->str_backward . " ";
$navi_string .= ($curr_pages < $all_pages) ? " " . $this->str_forward . "" . " " : " " . $this->str_forward . " ";
}
}
return "<span style='font-size:.7em; padding:3px 3px 4px 3px;'>" . $this->current_page_info() . $navi_string . "</span>";
}
function current_page_info() {
$cur_page = $this->set_page() + 1;
$total_pages = $this->get_num_pages();
// $page_info = " Page " . $cur_page . " of " . $total_pages . " ";
// return $page_info;
}
function show_go_to_page() {
$cur_page = $this->set_page() + 1;
$total_pages = $this->get_num_pages();
$options = "";
for ($i = 1; $i <= $total_pages; $i++) {
$options.="<option value=$i " . (($i == $cur_page) ? ' selected ' : '') . ">$i</option>";
}
$page_info = " Go to page <input type=text name=paginator_go_to_page id=paginator_go_to_page size=1 value=$cur_page />";
// $page_info.= "<select name=paginator_go_to_page2 >$options</select>";
return $page_info;
}
}
?>
tables.php
<?php
include("library/paginator.php");
?>
<div style="text-align:right;">
<?
$query = "select * from haves_settings";
$tab = mysql_query($query);
$row = mysql_fetch_array($tab);
$item_no = $row['items_to_show'];
$scroll = $row['scroll_interval'];
$online_paginate = new Paginator;
$online_paginate->sql = "select * from placing_item_bid where status='Active' and picture1!='' and selling_method!='want_it_now' and selling_method!='ads' and bid_starting_date <= now() and expire_date>=now() order by item_id desc"; // sql statement
$online_paginate->rows_on_page = $item_no;
$results = $online_paginate->get_page_result(); // result set
$num_rows = $online_paginate->get_page_num_rows(); // number of records in result set
$nav_links = $online_paginate->navigation(" | "); // the navigation links (define a CSS class
?>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#d79196" class="detail9txt">
<input type="hidden" value="2" name="len">
<td align="center" width="20%"><b>Picture</b> </td>
<td width="30%" align="center"><b>Name / Responses</b> </td>
<td width="50%" align="center"><b>Description</b> </td>
</tr><tr style="height:10px;"><td></td></tr>
<?
if ($num_rows > 0) {
while ($bestsellers_fetch = mysql_fetch_array($results)) {
$temp = $bestsellers_fetch['item_id'];
$sql = "SELECT count(`user_id`) as response FROM `watch_list` where `item_id`=$temp group by `item_id`";
$res = mysql_query($sql);
$response = mysql_fetch_row($res);
$counttop = $counttop + 1;
if (!empty($bestsellers_fetch['sub_title']))
$item_subtitle1 = $bestsellers_fetch['sub_title'];
else
$item_subtitle1 = substr($bestsellers_fetch['item_title'], 0, 20);
$item_title1 = substr($bestsellers_fetch['item_title'], 0, 40)
?>
<tr>
<td class="tr_botborder" style="vertical-align:middle;" width="20%" align="center"><div align="center"><img src="thumbnail/<?= $bestsellers_fetch['picture1']; ?>" alt="" width="79" height="70" border="0" /></div></td>
<td class="tr_botborder" style="vertical-align:middle;" width="30%" align="center"><div align="center"><span class="bestsellerstxt"><?= $item_subtitle1; ?> <?= $item_title1; ?><br/><?php if ($response[0] != '') { ?><a style="text-decoration:none;color:#336666;" href="detail.php?item_id=<?= $bestsellers_fetch['item_id']; ?>"> <?php echo $response[0] . ' responses'; ?></a> <?php } else { ?><span style="color:#666666;"><?php
echo '0 responses';
}
?></span></span></td>
<td class="tr_botborder" style="vertical-align:middle;" width="50%" align="center"><div align="center"><span class="bestsellerstxt"><?= html_entity_decode($bestsellers_fetch['detailed_descrip']); ?></span></td>
</tr>
<?
if ($counttop != 2) {
}
}
} else {
?>
<tr><td height="148" align="center" class="featxt">No Items Available</td></tr>
<?
}
?>
</table>
<div style="text-align: right;"><?php echo $nav_links; ?></div>
//wants content
$online_paginate1 = new Paginator;
$online_paginate1->sql = "select * from placing_item_bid where status='Active' and selling_method='want_it_now' order by item_id desc";
$online_paginate1->rows_on_page = $item_no1;
$result1 = $online_paginate1->get_page_result(); // result set
$want_total_records = $online_paginate1->get_page_num_rows(); // number of records in result set
$nav_links1 = $online_paginate1->navigation(" | "); // the navigation links (define a CSS class
?>
<div class="superbg">
<table cellspacing="0" cellpadding="5" width=100%>
<form name="want_form" action="myauction.php" method=post>
<tr bgcolor="#d79196" class="detail9txt">
<input type="hidden" name="len" value="<?= $want_total_records ?>">
<td align="center" width="30%"><b>Name / Responses</b> </td>
<td align="center" width="20%"><b>Picture</b> </td>
<td width="50%" align="center"><b>Description</b> </td>
</tr>
<?
if ($want_total_records > 0) {
while ($want_row = mysql_fetch_array($result1)) {
$tot_bid_sql = "select count(*) from want_it_now where wanted_itemid=" . $want_row[item_id];
$tot_bid_res = mysql_query($tot_bid_sql);
$tot_bids = mysql_fetch_array($tot_bid_res);
?>
<tr class="detail9txt">
<td class="tr_botborder" align="center" style="vertical-align:middle;" width="30%">
<a href="wantitnowdes.php?item_id=<?= $want_row['item_id'] ?>" class="header_text">
<? echo $want_row['item_title']; ?></a> <br/> <?
if ($tot_bids[0] != 0) {
?>
<a style="font-weight:normal;" href="wantitnowdes.php?item_id=<?= $want_row['item_id'] ?> " class="header_text"><? echo $tot_bids[0] . ' responses'; ?></a>
<?
} else {
echo $tot_bids[0] . ' responses';
}
?></td>
<td class="tr_botborder" style="vertical-align:middle;" width="20%" align="center">
<?
if (!empty($want_row['picture1'])) {
$img = $want_row['picture1'];
list($width, $height, $type, $attr) = getimagesize("images/$img");
$h = $height;
$w = $width;
if ($h > 50) {
$nh = 50;
$nw = ($w / $h) * $nh;
$h = $nh;
$w = $nw;
}
if ($w > 50) {
$nw = 50;
$nh = ($h / $w) * $nw;
$h = $nh;
$w = $nw;
}
?>
<!-- <img name="runimg" src="images/<? //echo $want_row['picture1']; ?>" border=1 width=<? //= $w; ?> height=<? //=$h ?> >-->
<img name="runimg" src="images/<? echo $want_row['picture1']; ?>" border=1 width="79" height="70" >
<?
} else {
?>
<img src="images/no_image.gif" border=1 name="runimg" >
<? } ?>
</td>
<td class="tr_botborder" style="vertical-align:middle;" width="50%" align="center"><div align="center"><span class="bestsellerstxt"><?= html_entity_decode($want_row['detailed_descrip']); ?></span></td>
</tr>
<?
} // while
} else {
?>
<tr>
<td width="3%"> </td>
<td width="97%" class="myauction3txt">There are no items in this section</td>
</tr>
<? } ?>
</table>
<div style="text-align: right;"><?php echo $nav_links1; ?></div>
</div>
Where is the problem ?
Paginator class uses the same query string "page" parameter to calculate the current page. If you add 2 or more Pagination in the same request, "page" will be shared by all instances, leading to this mess you described.
How to fix it ?
Tell the Paginator class which parameter to use in query string... follow this 2-step patch below :
Step 1 : replace constructor in Paginator class
// constructor
function Paginator($get_var=null) {
if ($get_var!=null) $this->get_var = $get_var;
}
Step 2 : update Paginator object creation (twice)
$online_paginate = new Paginator('page_table1');
and later :
$online_paginate1 = new Paginator('page_table2');
Hope this helps !