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.
Related
I am trying to create an update that whenever the user gets an offer lower than the last day/week average price they get points for it 50 for last day and 20 for last week
I am desperate I have been trying for the longest time to chage thing on the proyect and now when I try to update that for every time the condition is met to update the db, it does its work and see when the price is cheaper and where it isnt but never increases the score which bugs me a lot¿can someone help?
function check_if_offer_cheaper_with_twenty_than_previous_day($prodname, $price)
// Check if the price found by the user is 20% lower than the most recent available average price of the previous day
{
global $db;
$sql = 'SELECT AVG(prices.price) >"' . $price / 0.8 . '" AS cheaper_than_previous_day'
. " FROM prices"
. ' WHERE prices.prodname = "' . $prodname . '"' .
' AND prices.date = CURDATE() - INTERVAL 1 DAY';
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
if (isset($row['cheaper_than_previous_day'])) {
$query = "UPDATE users SET total_score = total_score +50,
score_this_month = score_this_month + 50 WHERE id = '" . $_SESSION['user']['id'] . "'";
mysqli_query($db, $query);
return $row['cheaper_than_previous_day'];
} else {
return true;
}
}
function check_if_offer_cheaper_with_twenty_than_previous_week($prodname, $price)
// Check if the price found by the user is 20% lower than the most recent average price available in the previous week
{
global $db;
$sql = 'SELECT AVG(prices.price) > "' . $price / 0.8 . '" AS cheaper_than_previous_week'
. " FROM prices"
. ' WHERE prices.prodname = "' . $prodname .
'" AND prices.date BETWEEN CURDATE() - INTERVAL 8 DAY AND CURDATE() - INTERVAL 1 DAY';
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
if (isset($row['cheaper_than_previous_week'])) {
$query = "UPDATE users SET total_score = total_score +20, score_this_month = score_this_month +50
WHERE id = '" . $_SESSION['user']['id'] . "'";
mysqli_query($db, $query);
return $row['cheaper_than_previous_week'];
} else {
return true;
}
}
MySQL syntax uses commas to separate the assignment pairs, like this
$query = "UPDATE users SET total_score = total_score +20,
score_this_month = score_this_month +50
WHERE id = '" . $_SESSION['user']['id'] . "'";
dev.mysql 8.0 update syntax
That is assuming that $_SESSION['user']['id'] does not evaluate to null.
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'];
}
// ...
}
Is this possible to do?
I have a query that is selecting all records from a table, which the results is based on a time field. This is a schedule of games for 17 weeks. What I am trying to do is create an array of just the current weeks games that have expired. In my code below, every expired game shows in the array. Is it possible to just create this separate array to only include the current week games? I still need to capture all the data, but am trying to create an array of data just for the current week as seen in the row expired portion of the code.
$latestweek = getCurrentWeek(); //gives the current week
for($wk=1;$wk<=17;$wk++){
$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;
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']]['sWinner'] = $row['result'];
$games[$row['gameID']]['startTime'] = $row['gameTimeEastern'];
if ($row['expired']){
$survGamesExpired_h[$e]=$row['homeID'];
$survGamesExpired_v[$e]=$row['visitorID'];
}
$expiredTeams = array_merge((array)$survGamesExpired_h,(array)$survGamesExpired_v);
}
}
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
I am trying to make a unique visitors counter for my pages using mysql and php. Im my DB table i have a "views" column and a "last_ip" column.
If the ip of the current user is equal to the last ip stored on DB the counter dies, if the current user ip is different from the last ip stored on DB the current user ip is stored as last ip on DB and the counter sums +1 to the views on DB.
The main idea is:
1 - check the ip of the current user and save it to variable $viewer_ip
2 - check the last ip stored on DB and save it to variable $last_viewer_ip
3 - compare those 2 variables, if $viewer_ip =! $last_viewer_ip the function should store $last_viewer_ip in "last_ip" field and sums +1 in "views" field. Else it should do nothing.
<?php
$viewer_ip = $user_ip = $h->cage->server->testIp('REMOTE_ADDR');
$sql = "SELECT post_last_viewer_ip FROM " . TABLE_POSTS . " WHERE post_id = %d";
$last_viewer_ip = $h->db->get_var($h->db->prepare($sql, $h->post->id));
if ($viewer_ip AND $viewer_ip != $last_viewer_ip) {
$sql = "UPDATE " . TABLE_POSTS . " SET post_last_viewer_ip = '" . $viewer_ip . "' WHERE post_id = %d";
$h->db->query($h->db->prepare($sql, $h->post->id));
}
if ($viewer_ip != $last_viewer_ip) {
$sql = "UPDATE " . TABLE_POSTS . " SET post_views = post_views + 1 WHERE post_id = %d";
$h->db->query($h->db->prepare($sql, $h->post->id));
}
?>
that code works in parts, cause it sums like 3 views, on each visit, as u can see, that code is a trash, cause i did it myself and i am no expert.
Anyone can try a fix on this? ty.
You need to store the session id of your visitors to the database to be able to do that kind of thing correctly. A unique visitor is considered one that is there for one specific session. If the user closes the browser and comes back, then it is another visitor.
If you want truly unique visitors, you need to store cookies too and use them to identify your visitors, but then again, cookie blocked? Cookie flushed? You're screwed...
Last method is to force a login, with a login you usually have a user_id, that user_id becomes your unicity.
I'll let you decide how you want to handle your unicity...
For the storage part, you need at least 1 table where you store the requests and identity of your requesters. Store in that table the following information:
Page/SpecificRequest
UserIP/SessionID/CookieID/UserId
RequestDate
RequestTime
Then on each page request, store a request in that table such as:
INSERT INTO myrequests VALUES(
$_REQUEST['URI'],
session_id(),
date('Y-m-d'),
date('G:i:s')
)
And then, to retrieve the unique visitor count, you just group on the data:
SELECT RequestDate, COUNT(*) AS uniquevisitors
FROM myrequests
GROUP BY RequestDate, session_id()
Good luck
Try it this way..
You need one separate table (TABLE_WITH_LOGS) for IP logs, which has 3 columns post_viewer_ip varchar(15), timestamp timestamp, post_id bigint (or whatever type you have for you post ids).
The code will look something like that one..
$timeout = 30*60; // count as a new visit after 30 minutes
$viewer_ip = $user_ip = $h->cage->server->testIp('REMOTE_ADDR');
// check if there is a record within the timeout period
$sql = "SELECT count(*) FROM " . TABLE_WITH_LOGS . " WHERE post_id = %d
AND ip = '%s' AND `timestamp` > NOW() - $timeout";
$rows = $h->db->get_var($h->db->prepare($sql, $h->post->id, $viewer_ip));
if ($rows == 0) { // no recent records in DB, insert new one
$sql = "INSERT INTO " . TABLE_WITH_LOGS . " SET post_viewer_ip = '" .
$viewer_ip . "', `timestamp` = NOW() WHERE post_id = %d";
$h->db->query($h->db->prepare($sql, $h->post->id));
// update counter
$sql = "UPDATE " . TABLE_POSTS . " SET post_views = post_views + 1
WHERE post_id = %d";
$h->db->query($h->db->prepare($sql, $h->post->id));
}
else { // there is at least one record, update it with current timestamp
$sql = "UPDATE " . TABLE_WITH_LOGS . " SET `timestamp` = NOW()
WHERE post_id = %d and post_viewer_ip = '$viewer_ip' LIMIT 1";
$h->db->query($h->db->prepare($sql, $h->post->id));
}
// cleanup table from time to time
if (rand(1,5)<2) {
$sql = "DELETE " . TABLE_WITH_LOGS . " WHERE `timestamp` < NOW() - $timeout";
$h->db->query($sql);
}
ps: you may skip part with timestamp update and always insert a new record. It will make less (only by one :)) SQL requests.
$timeout = 30*60; // count as a new visit after 30 minutes
$viewer_ip = $user_ip = $h->cage->server->testIp('REMOTE_ADDR');
// check if there is a record within the timeout period
$sql = "SELECT count(*) FROM " . TABLE_WITH_LOGS . " WHERE post_id = %d
AND ip = '%s' AND `timestamp` > NOW() - $timeout";
$rows = $h->db->get_var($h->db->prepare($sql, $h->post->id, $viewer_ip));
if ($rows == 0) { // no recent records in DB, update counter
$sql = "UPDATE " . TABLE_POSTS . " SET post_views = post_views + 1
WHERE post_id = %d";
$h->db->query($h->db->prepare($sql, $h->post->id));
}
// record last visit
$sql = "INSERT INTO " . TABLE_WITH_LOGS . " SET post_viewer_ip = '" .
$viewer_ip . "', `timestamp` = NOW() WHERE post_id = %d";
$h->db->query($h->db->prepare($sql, $h->post->id));
// cleanup table from time to time
if (rand(1,5)<2) {
$sql = "DELETE " . TABLE_WITH_LOGS . " WHERE `timestamp` < NOW() - $timeout";
$h->db->query($sql);
}