Remaining two rows get skipped in for-loop - php

I am programming a maintenaince thing for tournaments. Players are divided into "leagues". At the end, the first player of league x gets to play against the losers of league y. Winner of league y meets loser of league z etc. Then this rule gets repeated fot the numbers 2 and second lasts of the next league, 3rds and 3rd lasts of next league and so on. The number of leagues varies every time. Everything works really fine until it comes to the last two remaining players, let's say the middle player of league x don't get connected to the middle player of league y.
I found a way to work around this glitch but I'd rather have it working like it should.
This is my code: (khzz is the total amount of players without regarding leagues). Anybody sees what's wrong? Thanks!
for ($doen=0; $doen<=$hkzz; $doen++) {
$unid2 = "" . $doen . "-" . rand(1600,20000) . "";
$koppelpak = $conn->query ("SELECT * FROM poules WHERE poule='$startmet' AND amsyst='' ORDER BY ABS(ptn) DESC, karma DESC LIMIT 1");
//$kppk = mysqli_fetch_assoc($koppelpak);
while ($kppk = $koppelpak->fetch_array()) {
$conn->query("UPDATE poules SET amsyst='$unid2' WHERE koppel='$kppk[koppel]' ") or die(mysqli_error($conn));
echo "koppel " . $kppk['koppel'] . " uit poule " . $startmet . " tegen ";
$koppelpak2 = $conn->query ("SELECT * FROM poules WHERE poule='$volgende' AND amsyst='' ORDER BY ABS(ptn) ASC, karma ASC LIMIT 1");
while ($kppk2 = $koppelpak2->fetch_array()) {
$conn->query("UPDATE poules SET amsyst='$unid2' WHERE koppel='$kppk2[koppel]' ") or die(mysqli_error($conn));
echo "koppel " . $kppk2['koppel'] . " uit poule " . $volgende . "<br />";
}
$startmet = $startmet + 1;
$werk = $werk + 1;
if ($startmet>$hoep) { $startmet="1"; }
$volgende = $volgende + 1;
if ($volgende>$hoep) { $volgende="1"; }
//$volgen = $volgen + 1;
} // while
} // for

Related

Pull specific values from array to calculate

I have 2 tables. Table 1 is a schedule which holds weekly games. Table 2 is a separate table where you select just one team from the scheduled games for a week.
I am trying to get the difference in the score for the game that I chose a team for. So for a specific week, there are 13-16 games. I select 1 team from one of those games. If the team I pick wins, the result is the difference in the score. So if my team wins and the score is 27-10, I show 17 point. I have tried every way I can think to get this, but the best I seem to come up with is that it will calculate the last game of the week only, not the specific game that my team is involved in. The gameID is the key between both tables. Is it possible to do this? I thought by grabbing the values based on gameID from the array it would match it to the gameID associated with the selection from table 2.I am able to display the correct team, week by week, but not get the point differential for that specific game. Any ideas?
<?php
for($wk=1;$wk<=17;$wk++){
$allScoresIn = true;
$currentDT = date('Y-m-d H:i:s');
//get array of games
$games = array();
$sql = "select s.*, (DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > gameTimeEastern or DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > '" . $cutoffDateTime . "') as expired ";
$sql .= "from " . DB_PREFIX . "schedule s ";
$sql .= "where s.weekNum = " . $wk . " ";
$sql .= "order by s.gameTimeEastern, s.gameID";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$e = 0;
$homePtDiff = 0;
$visitorPtDiff = 0;
while ($row = $query->fetch_assoc()) {
$games[$row['gameID']]['gameID'] = $row['gameID'];
$games[$row['gameID']]['homeID'] = $row['homeID'];
$games[$row['gameID']]['visitorID'] = $row['visitorID'];
$games[$row['gameID']]['homeScore'] = $row['homeScore'];
$games[$row['gameID']]['visitorScore'] = $row['visitorScore'];
$games[$row['gameID']]['homeDiff'][$e] = $row['homeScore'] - $row['visitorScore'];
$games[$row['gameID']]['visitorDiff'][$e] = $row['visitorScore'] - $row['homeScore'];
$homePtDiff = $row['homeScore'] - $row['visitorScore'];
$visitorPtDiff = $row['visitorScore'] - $row['homeScore'];
if ((int)$row['homeScore'] != NULL && (int)$row['visitorScore'] != NULL) {
$scoreEntered = TRUE;
}else{
$scoreEntered = FALSE;
}
if ((int)$games[$row['gameID']]['homeScore'] > (int)$games[$row['gameID']]['visitorScore']) {
$games[$row['gameID']]['winnerID'] = $row['homeID'];
}else if ((int)$games[$row['gameID']]['homeScore'] < (int)$games[$row['gameID']]['visitorScore']){
$games[$row['gameID']]['winnerID'] = $row['visitorID'];
}
else{
$games[$row['gameID']]['winnerID'] = NULL;
}
$e++;
}
}
$sqlinner = "select * from " . DB_PREFIX . "pickmargin where weekNum = " . $wk . " and userID = " . $x . ";";
$queryinner = $mysqli->query($sqlinner);
if ($queryinner->num_rows > 0) {
$resultinner = $queryinner->fetch_assoc();
$currentPick = $resultinner['pickmargin'];
$currentGameID = $resultinner['gameID'];
$hidePicks = $resultinner['showPicks'];
$marginPts = 0;
$y_value = $x_value-1;
} else {
$currentPick = 'TBD';
}
if ($currentPick == $games[$row['gameID']]['homeID']){
$marginPts = (int)$games[$row['gameID']]['homeScore'] - (int)$games[$row['gameID']]['visitorScore'];
}
else{
$marginPts = (int)$games[$row['gameID']]['visitorScore'] - (int)$games[$row['gameID']]['homeScore'];
}
// ...
}

Pull values from a row based on ID

Hoping someone can shed light on this. I am trying to pull the value from 2 fields from a row and based on the row being expired, exclude those 2 values from a drop down list.
I have a table (schedule)
gameID
homeID
visitorID
gameTimeEastern
weekNum
each week there are matchups where 2 teams play each other. Those 2 teams are in a row based on gameID with a specific start time (gameTimeEastern).
I have a function that determines when the matchup is locked, meaning the game has started:
function gameIsLocked($gameID) {
//find out if a game is locked
global $mysqli, $cutoffDateTime;
$sql = "select (DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > gameTimeEastern or DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR) > '" . $cutoffDateTime . "') as expired from " . DB_PREFIX . "schedule where gameID = " . $gameID;
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
return $row['expired'];
}
$query->free;
die('Error getting game locked status: ' . $mysqli->error);
This basically determines if the row is expired (gameTimeEastern has passed). I then have a drop down on a form that has a list of all the teams from each matchup for that week.If the row is expired, then I do not want to include the homeID or visitorID from that row in the drop down.
On my page I am trying to show those teams from the expired row but it is failing as the page stops processing when it hit this:
//get expired teams
$expiredGames =gameIsLocked(gameID);
// echo 'Expired games are GAME ' . $expiredGames . '<br>';
for ($eti=1; $eti<=$gameID; $eti++)
{
if ($gameID[$eti]>''){
$sql = "select * from " . DB_PREFIX . "schedule WHERE gameID = '" . $gameID[$eti] . "';";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$result = $query->fetch_assoc();
$expiredHomeTeam = $result['homeID'];
$expiredVisitorTeam = $result['visitorID'];
}
}
echo 'Expired teams for GAME '.$gameID.' are '.$expiredHomeTeam.' and '.$expiredVisitorTeam.'<br>';
}
NEW CODE - Actually giving me the first result
//get expired teams
$expiredGames =gameIsLocked(gameID);
$sql = "select * from " . DB_PREFIX . "schedule WHERE weekNum = '6';";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$result = $query->fetch_assoc();
$expiredHomeTeam = $result['homeID'];
$expiredVisitorTeam = $result['visitorID'];
}
echo 'Expired teams for GAME ' . $expiredGames . ' are '.$expiredHomeTeam.' and '.$expiredVisitorTeam.'<br>';
Ended up using the SQL query to schedule to get results I needed. Thanks for the direction. The logic was already there, just needed to add an if statement to how I populated the array for teams in the drop down.

How can I perform these MySQL subqueries in a cleaner way?

Using legacy code which uses mysql instead of mysqli/pdo so don't worry about this, I'll update the queries for this later.
Even though my current method works, I'm positive there is a cleaner way of doing this rather than a query and 3 subqueries. I mainly want to learn how to better enhance my queries and minimizing the amount of them.
What I'm trying to do is
echo out all the data for each date with the date displayed on top
Display the count of entries for each user on that particular day next to the user
For each date, at the bottom of the above 2 bits of data, display the user/s with the highest number of entries
$query = mysql_query('SELECT * FROM entries GROUP BY DATE(dt)');
$g = 0;
while ($row = #mysql_fetch_array($query))
{
$group[$g] = date('y-m-d', strtotime($row['dt']));
echo $group[$g] . "<br />";
//display the person's name for today with their count
$dayquery = mysql_query('SELECT *, COUNT(username) as total FROM entries WHERE DATE(dt) = "'.$group[$g].'" GROUP BY username ORDER BY COUNT(username) DESC');
while ($today = #mysql_fetch_array($dayquery))
{
echo $today['first_name'] . " | " . $today['total'] . "<br />";
}
//display the highest count for today
$topquery = mysql_query('SELECT COUNT(username) as highest FROM entries WHERE DATE(dt) = "'.$group[$g].'" GROUP BY username ORDER BY COUNT(username) DESC LIMIT 1');
while ($toptoday = #mysql_fetch_array($topquery))
{
echo "Highest today: " . $toptoday['highest'] . "<br /><br />" ;
}
//display the users with the highest count for today
echo "Highest users: ";
$userstopquery = mysql_query('SELECT *, COUNT(username) as total FROM entries WHERE DATE(dt) = "'.$group[$g].'" AND COUNT(username) = "' . $toptoday['highest'] . '" AND GROUP BY username');
while ($topusers = #mysql_fetch_array($userstopquery))
{
echo $topusers['first_name'] . "<br />" ;
}
$g++;
}
The trouble I'm having is that when I try and reduce these subqueries and use MAX it will only output the highest count but not all the data for each date, which is what I need, including output of the user/s with the most amount of entries for that given day.
You could start with something like this. Note that I'm not using PHP's mysql_ API as it was deprecated 3 or 4 years ago...
require('path/to/mysqli/connection/stateme.nts');
$array = array();
$query = "
SELECT e.dt
, e.username
, COUNT(*) ttl
FROM entries e
GROUP
BY e.dt
, e.username
ORDER
BY e.dt, ttl DESC;
";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
print_r($array);

Can't get score to update with this mysql statement

I'm guessing that I'm just a little rusty or something because it seems like this should be working. Am I missing something here...
Here is the code I am trying to use...
<?php
echo dbConn();
$existing_time = mysql_result(mysql_query("SELECT p_time FROM scores WHERE p_uid=$uid"), 0);
$existing_category = mysql_result(mysql_query("SELECT p_cat FROM scores WHERE p_uid=$uid AND p_cat=$pieces"), 0);
if ($existing_category == "") {
mysql_query(
"INSERT INTO scores VALUES (
'',
'$uid',
'$pusername',
'$time',
'$pieces'
)");
} elseif ($existing_time <= $time) {
echo "No Change! Old Score Was Better (Lower)";
} elseif ($existing_time > $time) {
mysql_query("UPDATE scores SET p_time = " . $time . " WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
};
?>
Now... Here is what I am trying to do...
I am collecting info from the database where the users username AND category match. If the category for that user does not exist, it inserts the latest score. (This much works.)
Then, if the category does exist but the old score is better, it just does nothing. (This part works too)...
However, what I can't seem to do is get it to update the last score, if the current score is better (lower score, since this is a time based game.) It doesn't update the score.
I am trying it this way: By updating a row in "scores" where the USERNAME and the CATEGORY match at the same time.
Please note... where it says "pieces". this is a category. Where it says "time", this is a score. The score is returned as 00:00:00 for hours minutes and seconds.
EXAMPLE: (in parentheses is the database row name)
id (ID) = just KEY id in sequencial order
user id (p_uid) = 123456789
username (p_username) = somename
score (p_time) = 00:01:03
category (p_cat) = 10
Change you update statement to:
mysql_query("UPDATE scores SET p_time = '" . $time . "' WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
You have missed quotes in the update statement around $time.

PHP array logic

How can I set up an array of subjects with boolean values or test scores stored in them?
I am trying to display a gold medal if someone makes high scores on every test in a subject.
I wish I could be more clear in the framing of this question, but here is some code to help elucidate:
$resTestsQryStr = "SELECT TestID, Subject FROM Tests
WHERE " . $edstr . " AND " . $plstr . " AND " . $levelStr . " GROUP BY Subject";
$resTests = mysql_query($resTestsQryStr);
while ($rowT=mysql_fetch_array($resTests))
{
$subject=$rowT['Subject'];
$tID=$rowT['TestID'];
$resScore= mysql_query("SELECT Score FROM CompletedTests WHERE UserNum = '$userNum' AND TestID = '$tID'");
$rowScore= mysql_fetch_array($resScore);
if ($rowScore['Score'] < 100){
$medalWinArray[$subject]= false;
break;
}
else
$medalWinArray[$subject]= true;
}
I think this should do it:
SELECT Subject, MIN(Score) >= 100 GoldMedal
FROM Tests t
JOIN Completed Tests c ON c.TestID = t.TestID
WHERE $edstr AND $plstr AND $level
AND c.userNum = '$userNum'
GROUP BY Subject

Categories