sort asc desc php, mysql - php

I have some code for ascending and descending sort, when click on link, table will be sorted asc and after another they will be sort desc. Generally code is working but they don't return first and last field from database. When sort desc don't return last and when asc then don't return first field. I will come piece of code here. Somebody to help ? Thanks.
this is the link for request
echo "<th>ID
<a href='sort_user.php?sortItemsId&order=" . (isset($_GET['order'])?!$_GET['order']: 1) . "'>
<i class='fa fa-sort' aria-hidden='true'></i>
</a>
</th>";
if (isset($_REQUEST["sortItemsId"])) {
$isAsc = isset($_GET['order'])? (bool) !$_GET['order']: 1;
$sql = "SELECT id, name, number, email, recovery_email, address FROM users ORDER BY id " .($isAsc?"ASC":"DESC").";";
$query = mysqli_query($db, $sql);
.....
}

You have nested while loops in your code:
while($row = mysqli_fetch_object($query)) {
//some code
//$row is first object
while($row = mysqli_fetch_object($query)) {
//printing data
//$row is replaced by second object and so on
}
}

I will post now full code with printing data. I got result but don't get last field when sorting desc and don't get first field when sorting asc
if (isset($_REQUEST["sortItemsId"])) {
$isAsc = isset($_GET['order'])? (bool) !$_GET['order']: 1;
$sql = "SELECT id, CRMContact, CRMOrganization, username, recovery_email, status FROM tb_users ORDER BY id " .($isAsc?"ASC":"DESC").";";
$query = mysqli_query($db, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_object($query)) {
echo "<div class='container'><table class='table table-striped'><thead>";
echo " <tr><th>ID
<a href='existing_user.php?sortItemsId&order=" . (isset($_GET['order'])?!$_GET['order']: 1) . "'>
<i class='fa fa-sort' aria-hidden='true'></i>
</a>
</th> <th>CRM Contact</th><th>CRM Organization</th>";
echo "<th>Username</th><th>Recovery email</th><th>Status</th><th>Actions</th></tr></thead>";
$i = 0;
while ($row = mysqli_fetch_object($query)) {
$i++;
$id = $row->id;
echo "<tbody>
<tr>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'>$row->id</td>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'>$row->CRMContact</td>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'>$row->CRMOrganization</td>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'><a href='edit_user.php?idEdit=$row->id'>$row->username</a></td>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'>$row->recovery_email</td>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'>$row->status</td>
<td style='background-color:" . (($i % 2 == 0) ? '#fff' : '#f9f9f9') . "'>
<div class='btn-group'>
<button type='button' class='btn btn-default dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false' style='background-color: #4076BC; color: #fff;'>
<i class='fa fa-fire' aria-hidden='true'></i>
Action <span class='caret'></span>
</button>
<ul class='dropdown-menu'>
<li><a href='view_user.php?viewId=$row->id'>View</a></li>
<li><a href=''>Edit</a></li>
<li><a href='existing_user.php?deleteUser=$row->id'>Delete</a></li>";
?>
<?php
if ($row->deactivated == 1) {
echo "<li><a href='existing_user.php?deactivateUserAcc=activate&id=$id'>Activate</a></li>";
} else {
echo "<li><a href='existing_user.php?deactivateUserAcc=deactivate&id=$id'>Deactivate</a></li>";
}
"</ul>
</div>
</td>
</tr>
</tbody>";
}
echo "</table></div>";
}
} else if (mysqli_num_rows($query) == 0) {
echo "<script type='text/javascript'>alert('Database is empty.');</script>";
} else {
echo "<script type='text/javascript'>alert('Something went wrong.');</script>";
}
}

Related

Asking how can I hide table?

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>

Issue with $where_stmt syntax and } placement

I'm very new to PHP and MySQLI, however, I have been dabbling with them for a couple of years.
I am working on adding a search function for some photos I have on my website based off of 3 criteria.
I've been successful in implementing the script on a different page, which does not include the syntax for the page limits. However, now, when I add in my $where_stmt code, I end up with some errors, and I believe it has to do with the placement of a needed }.
The script in question is:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (!defined('DB_SERVER')) define('DB_SERVER', 'xxx');
if (!defined('DB_USER')) define('DB_USER', 'xxx');
if (!defined('DB_PASSWORD')) define('DB_PASSWORD', 'xxx');
if (!defined('DB_TABLE')) define('DB_TABLE', 'xxx');
// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
// This first query is just to get the total count of rows
$sql = "SELECT COUNT(*) FROM tbl_photos";
$query = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_row($query);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 16;
// 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;
if(isset($_POST['submit']))
if(isset($_GET['go']))
if(isset($_REQUEST['submited'])) {
$tid = $_POST['tID'];
$lvmid = $_POST['lvmID'];
$lid = $_POST['lID'];
$where_stmt="";
// query only for LuchtvaartmaatschappijID (LVMID)
if((isset($lvmid) && !empty($lvmid)) && (!isset($tid) || empty($tid)) && (!isset($lid) || empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."'";
}
// query only for ToestelID
elseif((isset($tid) && !empty($tid)) && (!isset($lvmid) || empty($lvmid)) && (!isset($lid) || empty($lid)))
{
$where_stmt="WHERE t.toestelID = '".$tid."'";
}
// query only for luchthaven
elseif((isset($lid) && !empty($lid)) && (!isset($lvmid) || empty($lvmid)) && (!isset($tid) || empty($tid)))
{
$where_stmt="WHERE img_location = '".$lid."'";
}
// query only for Luchtvaartmaatschappij and Toestel
elseif((isset($lvmid) && !empty($lvmid)) && (isset($tid) || !empty($tid)) && (!isset($lid) || empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and t.toestelID='".$tid."'";
}
// query only for Luchtvaartmaatschappij and luchthaven
elseif((isset($lvmid) && !empty($lvmid)) && (isset($lid) || !empty($lid)) && (!isset($tid) || empty($tid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and img_location = '".$lid."'";
}
// query for luchtvaartmaatschappij, toestel and luchthaven
elseif((isset($lvmid) && !empty($lvmid)) && (isset($tid) && !empty($tid)) && (isset($lid) && !empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and t.toestelID='".$tid."' and img_location = '".$lid."'";
}
else
{
//where statement should be excluded as no filters are available
}
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "
SELECT randimgID, img_location, img_lvm, img_file, img_nmr, img_t, t.toestel, l.luchthavennaam, lvm.luchtvaartmaatschappij, lvm.luchtvaartmaatschappijID, t.toestelID
FROM tbl_photos p
LEFT JOIN tbl_luchthaven l
ON p.img_location = l.luchthavenID
LEFT JOIN tbl_luchtvaartmaatschappij lvm
ON p.img_lvm = lvm.IATAcode
LEFT JOIN tbl_toestel t
ON p.img_t = t.toestelID
$where_stmt
ORDER BY lvm.luchtvaartmaatschappij, t.toestel ASC, p.img_nmr ASC $limit";
$query = mysqli_query($mysqli, $sql);
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($query);
// This shows the user what page they are on, and the total number of pages
$textline1 = "beelden (<b>$rows</b>)";
$textline2 = "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 .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'">vorige</a> </li>';
// 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 .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> </li>';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= '<li class="page-item active">
<a class="page-link" href="#">'.$pagenum.' <span class="sr-only">(current)</span></a>
</li>';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> </li> ';
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 .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">volgende</a> </li>';
}
}
$list = '';
$items_in_row = 2 ;
$index = 0 ;
echo "<table width='100%' cellspacing='1' border='0'>
<tr>";
while($row = mysqli_fetch_assoc($query)) {
$img_location = $row['luchthavennaam'];
$img_lvm = $row['img_lvm'];
$l = htmlspecialchars($row['luchtvaartmaatschappij']);
$lvmID = $row['luchtvaartmaatschappijID'];
$img_nmr = $row['img_nmr'];
$t = $row['toestel'];
$tid = $row['toestelID'];
$f = $row['img_file'];
$rID = $row['randimgID'];
$img_file = $row['img_file'];
$image = "http://globe-trekking.com/vg/img/gallery/$img_lvm/$img_file";
$link = "http://globe-trekking.com/vg/gallery/details.php?pid=$rID&lvmID=$lvmID&in=$img_nmr";
$index++ ;
echo "<td width='370' align='left' valign='top' bgcolor='#292960'> ";
echo "<table width='540' border='0' cellpadding='0' cellspacing='0'>";
echo "<tbody>";
echo " <tr>";
echo " <td height='15' colspan='3' bgcolor='#292960'></td>";
echo " </tr>";
echo " <tr>";
echo " <td height='15' colspan='3' bgcolor='#000033'></td>";
echo " </tr>";
echo "<tr>";
echo " <td width='15' bgcolor='#000033'> </td>";
echo " <td bgcolor='#000033'><a href='" . $link ."'><img src='".$image."' width='510'></a></td>";
echo " <td width='15' bgcolor='#000033'></td>";
echo "</tr>";
echo "<tr>";
echo " <td bgcolor='#000033'> </td>";
echo " <td bgcolor='#000033'><table width='510' border='0' align='center' cellpadding='0' cellspacing='0'>";
echo " <tr>";
echo " <td height='15' colspan='2' valign='top' style='text-align: left'> </td>";
echo " </tr>";
echo " <tr>";
echo " <td width='72%' valign='top' style='text-align: left'><span style='font-size: 18px; color: #DEDEDE'><a class='airline' href='gallery_lvm.php?lvmid=$lvmID'>" . $l . "</a></span></td>";
echo " <td width='28%' style='text-align: left'><span style='font-size: 14.5px; color: #DEDEDE'>Reg: <a class='airline' href='gallery_reg.php?reg=$img_nmr'>" . $img_nmr . "</a></span></td>";
echo " </tr>";
echo " <tr>";
echo " <td height='10' colspan='2' valign='top' style='text-align: left'></td>";
echo " </tr>";
echo " <tr>";
echo " <td valign='top' style='text-align: left'><span style='font-size: 14.5px; color: #DEDEDE'><a class='airline' href='gallery_t.php?tid=$tid'>" . $t . "</a></span></td>";
echo " <td style='text-align: left'> </td>";
echo " </tr>";
echo " <tr>";
echo " <td height='10' colspan='2' valign='top' style='text-align: left'></td>";
echo " </tr>";
echo " <tr>";
echo " <td colspan='2' valign='top' style='text-align: left'><span style='font-size: 14.5px; color: #DEDEDE'>" . $img_location . "</span><br>
<br>
</td>";
echo " </tr>";
echo " <tr>";
echo " <td style='text-align: left'> </td>";
echo " <td style='text-align: left'> </td>";
echo " </tr>";
echo " </table></td>";
echo " <td bgcolor='#000033'> </td>";
echo "</tr>";
echo "<tr>";
echo " <td> </td>";
echo " <td> </td>";
echo " <td> </td>";
echo "</tr>";
echo " </tbody>";
echo " </table>";
echo " </td>";
if ($index%$items_in_row == 0){
echo " </tr>";
echo " <tr>";
}
}
echo " </tr>";
echo " </table>";
// Close your database connection
mysqli_close($mysqli);
?>
<br />
<nav aria-label="Page Navigation">
<ul class="pagination justify-content-center">
<div class="pagination"><?php echo $paginationCtrls; ?></div>
</ul>
</nav>
<br />
</div>
<br />
<br />
</div>
<?php include '../includes/menu/footer.php'; ?>
</body>
</html>
When I add it after the last else statement, I end up with an error that indicate
Notice: Undefined variable: where_stmt in /xxx/xxx/public_html/vg/gallery/search_post.php on line 174
// query for luchtvaartmaatschappij, toestel and luchthaven
elseif((isset($lvmid) && !empty($lvmid)) && (isset($tid) && !empty($tid)) && (isset($lid) && !empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and t.toestelID='".$tid."' and img_location = '".$lid."'";
}
else
{
//where statement should be excluded as no filters are available
}
}
If I add it just before the mysqli_close() then it throws an error of:
PHP Notice: Undefined variable: paginationCtrls in
/xxx/xxx/public_html/vg/gallery/search_post.php on line 325
If I leave it out all together I get the following red x error in the web editor my hosting company provides me with:
Unexpected syntax, error $E0F
At this point, I'm not sure where this should be placed.
I should note that I can get the code to work when I get rid of the $where_stmt and the code above the $sql query.
I can recommend you to have a look at ORM libraries like http://propelorm.org/documentation/reference/model-criteria.html#finding-objects to avoid handwritten SQL and concatenated where clauses.
Also make sure that $paginationCtrls is declared before using it.

How to refresh a database query using jQuery

I'm working on a real basic chat that is mostly php powered. I'd like to use jQuery to check for new messages and update the #cbox div every few seconds. So far I have tried accomplishing that using the code below. For a frame of reference, this is my first time including jQuery into any of my scripts, so the problem is likely a very simple error that I am overlooking in my newbishness.
The problem I'm running into is the #cbox div displays blank, it doesn't seem to be calling to chat_post.php at all. I will post that code as well, in case the problem is with that and not with my jQuery. To fix, I tried also including <div id='cbox'> in chat_post.php, but that yielded no results. At this point, I'm pretty much grasping at straws.
<div id='sb_content'>
<center><div id='chat'>
<div id='ribbon' style='position: relative; margin-top:-50px; margin-left:-32px;'><center><span class='ribbon'>chat box</span></center></div>
<div style='margin-top: -20px;'><center><span style='text-shadow: 0 0 0.2em #000;' class='admin'>admin</span> || <span style='text-shadow: 0 0 0.2em #000;' class='mod'>mod</span></center></div>
<div id="cbox">
<script>
$(document).ready(function() {
setInterval(function(){getUpdates()}, 2000);
});
function getUpdates() {
$("#cbox").load("chat_post.php");
}
</script>
</div>
<form name="message" method='post' action="chat_post.php" id="cbox_input">
<input name="usermsg"id='usermsg' type="text" size="63" maxlength="255" />
</form>
</div></center>
</div>
chat_post.php
<div id='cbox' align='left'>
<?php
$username = $_SESSION['login'];
$ug = $_SESSION['user_group'];
// Display messages
$sql = <<<SQL
SELECT *
FROM `chat_entries`
ORDER BY `ts` DESC
LIMIT 0,50
SQL;
$result = $db->query($sql);
$count = $result->num_rows;
if ($count != 0){
while ($row = mysqli_fetch_array($result)) {
$c_name = $row['author'];
$c_text = $row['text'];
$c_ts = $row['ts'];
$c_id = $row['id'];
$sqlm = <<<SQL
SELECT *
FROM `users`
WHERE username = '$c_name'
SQL;
$resultm = $db->query($sqlm);
$countm = $resultm->num_rows;
if ($count != 0){
while ($rowm = mysqli_fetch_array($resultm)) {
$c_level = $rowm['user_group'];
}
}
if ($c_level == 'mod') {
echo "
<a href='/user/" . $c_name . "' class='mod'>" . $c_name . "</a>
";
}
if ($c_level == 'admin') {
echo "
<a href='/user/" . $c_name . "' class='admin'>" . $c_name . "</a>
";
}
if ($c_level == 'member') {
echo "
<a href='/user/" . $c_name . "' class='member'>" . $c_name . "</a>
";
}
if ($c_level == 'guest') {
echo "
<i>" . $c_name . "</i>
";
}
echo "
: " . $c_text . "<div id='cbox_div'>";
echo "<span style='float:left;'><i>" . $c_ts . "</i></span>";
echo "<span style='float:right;'>";
if ($ug == 'mod' || $ug == 'admin'){
echo " <a href='#'>Delete</a> || <a href='#'>Block</a> ||";
}
if ($_SESSION['login']) {
echo "Report</span></div>
";
}
}
}
?>
After removing the extra id on chat_post.php, my code worked just fine. Funny how something so simple can really mess things up. (: Thank you everyone for your help!

call or create session variable in SUM

I am not very familiar with PHP or MySQL, but after researching here I have been able to learn and get very close to what I need and build my first sum query. I am trying to read the database and sum values based on several variables.
I need the reservation_pax from the reservations table where reservation_time is 8:00 where reservation_hidden = 0 and reservation_date is something. I can manually enter the date and it works. I am now trying to use a session code already in the script or find a way to to dynamically add based on selected date.
Here is the code I have working without the dynamic aspect or session.
$result = mysql_query("SELECT SUM(reservation_pax)
FROM reservations
WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'") ;
if ($result === false) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result)) {
echo $row['SUM(reservation_pax)'];
}
Here is the full code of the page where I entered the above addition. Can anyone help me figure out how to call the selected date rather than having to manually enter.
<!-- Begin reservation table data -->
<br/>
<table class="global resv-table-small" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<?php
echo "<td class='noprint'> </td>";
echo "<td>Time</td>";
echo "<td>Guests/Type</td>";
echo "<td>Name</td>";
echo "<td>Special Instructions/Notes</td>";
echo "<td class='noprint'>Table</td>";
echo "<td class='noprint'>Status</td>";
echo "<td class='noprint'>Created</td>";
echo "<td class='noprint'>Details/Delete</td>";
echo "</tr>";
// Clear reservation variable
$reservations ='';
if ($_SESSION['page'] == 1) {
$reservations = querySQL('all_reservations');
}else{
$reservations = querySQL('reservations');
}
// reset total counters
$tablesum = 0;
$guestsum = 0;
if ($reservations) {
//start printing out reservation grid
foreach($reservations as $row) {
// reservation ID
$id = $row->reservation_id;
$_SESSION['reservation_guest_name'] = $row->reservation_guest_name;
// check if reservation is tautologous
$tautologous = querySQL('tautologous');
echo "<tr id='res-".$id."'>";
echo "<td";
// daylight coloring
if ($row->reservation_time > $daylight_evening){
echo " class='evening noprint'";
}else if ($row->reservation_time > $daylight_noon){
echo " class='afternoon noprint'";
}else if ($row->reservation_time < $daylight_noon){
echo " class='morning noprint'";
}
echo " style='width:10px !important; padding:0px;'> </td>";
echo "<td id='tb_time'";
// reservation after maitre message
if ($row->reservation_timestamp > $maitre['maitre_timestamp'] && $maitre['maitre_comment_day']!='') {
echo " class='tautologous' title='"._sentence_13."' ";
}
echo ">";
echo "<strong>".formatTime($row->reservation_time,$general['timeformat'])."</strong></td>";
echo "<td id='tb_pax'><strong class='big'>".$row->reservation_pax."</strong> <span class='noprint'>";
printType($row->reservation_hotelguest_yn);
//echo "<img src='images/icons/user-silhouette.png' class='middle'/>";
echo "</span></td><td style='width:10%' id='tb_name'><span class='noprint'>".printTitle($row->reservation_title)."</span><strong> <a id='detlbuttontrigger' href='ajax/guest_detail.php?id=".$id."'";
// color guest name if tautologous
if($tautologous>1){echo" class='tautologous tipsy' title='"._tautologous_booking."'";}
echo ">".$row->reservation_guest_name."</a></strong>";
// old reservations symbol
if( (strtotime($row->reservation_timestamp) + $general['old_days']*86400) <= time() ){
echo "<img src='images/icons/clock-bolt.png' class='help tipsyold middle smicon' title='"._sentence_11."' />";
}
// recurring symbol
if ($row->repeat_id !=0) {
echo " <img src='images/icons/loop-alt.png' alt='"._recurring.
"' title='"._recurring."' class='tipsy' border='0' >";
}
echo"</td><td style='width:10%' id='tb_note'>";
if ($_SESSION['page'] == 1) {
echo $row->outlet_name;
}else{
echo $row->reservation_notes;
}
echo "</td>";
if($_SESSION['wait'] == 0){
echo "<td class='big tb_nr' style='width:85px;' id='tb_table'><img src='images/icons/table_II.png' class='tipsy leftside noprint' title='"._table."' /><div id='reservation_table-".$id."' class='inlineedit'>".$row->reservation_table."</div></td>";
}
echo "<td class='noprint'><div>";
getStatusList($id, $row->reservation_status);
echo "</div></td>";
echo "<td class='noprint'>";
echo "<small>".$row->reservation_booker_name." | ".humanize($row->reservation_timestamp)."</small>";
echo "</td>";
echo "<td class='noprint'>";
// MOVE BUTTON
// echo "<a href=''><img src='images/icons/arrow.png' alt='move' class='help' title='"._move_reservation_to."'/></a>";
// WAITLIST ALLOW BUTTON
if($_SESSION['wait'] == 1){
$leftspace = leftSpace(substr($row->reservation_time,0,5), $availability);
if($leftspace >= $row->reservation_pax && $_SESSION['outlet_max_tables']-$tbl_availability[substr($row->reservation_time,0,5)] >= 1){
echo" <a href='#' name='".$id."' class='alwbtn'><img src='images/icons/check-alt.png' name='".$id."' alt='"._allow."' class='help' title='"._allow."'/></a> ";
}
}
// EDIT/DETAIL BUTTON
echo "<a href='?p=102&resID=".$id."'><img src='images/icons/pen-fill.png' alt='"._detail."' class='help' title='"._detail."'/></a> ";
// DELETE BUTTON
if ( current_user_can( 'Reservation-Delete' ) && $q!=3 ){
echo"<a href='#modalsecurity' name='".$row->repeat_id."' id='".$id."' class='delbtn'>
<img src='images/icons/delete.png' alt='"._cancelled."' class='help' title='"._delete."'/></a>";
}
echo"</td></tr>";
$tablesum ++;
$guestsum += $row->reservation_pax;
}
}
?>
</tbody>
<tfoot>
<tr style="border:1px #000;">
<td class=" noprint"></td><td></td>
<td colspan="2" class="bold"><?php echo $guestsum;?> <?php echo _guest_summary;?></td>
<td></td>
<td colspan="2" class="bold"><?php echo $tablesum;?> <?php echo _tables_summary;?></td>
<td colspan="2" class="bold"><?php
$result = mysql_query("SELECT SUM(`reservation_pax`) FROM `reservations` WHERE `reservation_time` = '8:00:00' AND `reservation_date` = '{$_SESSION['selectedDate']}' AND `reservation_hidden` ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>
<?php echo '/ 40 ', _guest_summary, ' -8:00 AM';?></td>
<td></td>
<?php
if($_SESSION['wait'] == 0){
//echo "<td></td>";
}
?>
</tr>
</tfoot>
</table>
<!-- End reservation table data -->
you can use alias field, as:
$result = mysql_query("SELECT SUM(reservation_pax) AS reserve_sum
FROM reservations WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'"
) ;
....
and get access it as:
while($row = mysql_fetch_array($result))
{
echo $row['reserve_sum'];
}
$result = mysql_query("SELECT SUM(reservation_pax) FROM reservations WHERE reservation_time = '8:00:00' AND reservation_date = '{$_SESSION['selectedDate']}' AND reservation_hidden ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>

Issues with Pagination in PHP

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 !

Categories