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'];
}
// ...
}
Related
I'm building a job search site and I have 3 tables.
1: jobs_table: id, user_id, job_title, location, job_description, currency, salary, salary_type, employment_type, post_time, visiblity
2: applications_table: id, creator_id, applicant_id, job_id, status
3: user_table: id, profile_picture, first_name, last_name, phone_number, email_address, password, data, verification_key, modify_date
Currently, I'm selecting from the jobs_table based on user input (PHP code below), however, I'm trying to also display to the user which jobs they have already applied for and to do this I need to select from the Jobs_table (get the jobs data as I'm already doing), but also select from the applications_table with the current users ID to check if there is a row with the applicant_id and job_id if this row exists then the user has already applied for that position.
Any help is much appreciated.
PHP
$conditions = [];
// Start by processing the user input into a data structure that can be used to construct the query
if (!empty($t)) {
$conditions[] = [
['job_title', 'LIKE', '%' . $t . '%'],
];
}
if (!empty($l)) {
$conditions[] = [
['location', '=', $l],
];
}
if (!empty($s)) {
$conditions[] = [
['salary', '>=', $s],
];
}
// Loop the conditions and process them into valid SQL strings
$bindValues = [];
$whereClauseParts = [];
foreach ($conditions as $conditionSet) {
$set = [];
foreach ($conditionSet as $condition) {
list($fieldName, $operator, $value) = $condition;
$set[] = "`{$fieldName}` {$operator} :{$fieldName}";
$bindValues[$fieldName] = $value;
}
$whereClauseParts[] = implode(' OR ', $set);
}
$statement = "SELECT * FROM 001_jobs_table_as WHERE visiblity = 2";
if (!empty($whereClauseParts)) {
$statement .= " AND (" . implode(') AND (', $whereClauseParts) . ")";
}
/* Pagination Code starts */
$per_page_html = '';
$page = 1;
$start=0;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start=($page-1) * ROW_PER_PAGE;
}
$limit=" limit " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $dbh->prepare($statement);
$pagination_statement->execute($bindValues);
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$per_page_html .= "<div class='page_row_selector'>";
$page_count=ceil($row_count/ROW_PER_PAGE);
if($page_count>1) {
for($i=1;$i<=$page_count;$i++){
if($i==$page){
$per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page active_page" />';
} else {
$per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page" />';
}
}
}
$per_page_html .= "</div>";
}
$query = $statement.$limit;
$pdo_statement = $dbh->prepare($query);
$pdo_statement->execute($bindValues);
$result = $pdo_statement->fetchAll();
if(empty($result)) { ?>
<div class="job_card">
<h1 class="display-5 text-center no_result_message"> No match found. </h1>
</div>
<?php }else{
foreach($result as $row) {
$user_id = $row['user_id'];
$job_key = $row['id'];
$job_title = $row['job_title'];
$location = $row['location'];
$job_description = $row['job_description'];
$employment_type = $row['employment_type'];
$salary = $row['salary'];
$salary_type = $row['salary_type'];
$currency = $row['currency'];
$post_time = $row['post_time'];
$user_id = $row['user_id'];
$to_time = time();
$from_time = strtotime($post_time);
$time_elapsed = $to_time - $from_time;
$seconds = round(abs($time_elapsed));
$minutes = round(abs($time_elapsed) / 60);
$hours = round(abs($time_elapsed) / 3600);
$days = round(abs($time_elapsed) / 86400);
$weeks = round(abs($time_elapsed) / 604800);
// display job information in here.
} ?>
UPDATE:
I have now revised my SELECT query to the following:
$statement = "SELECT * FROM 001_jobs_table_as jt";
$statement .= " LEFT JOIN 001_application_table_as at ON at.job_id = jt.jt_id";
$statement .= " RIGHT JOIN 001_user_table_as ut ON ut.id = at.applicant_id";
$statement .= " WHERE jt.visiblity = 2";
However, I'm getting duplicates in the results, every user that applies for a job duplicates that job in the results.
What about using LEFT JOIN?
The LEFT JOIN keyword returns all records from the left table
(table1), and the matched records from the right table (table2).
SELECT *, id AS jt_id FROM jobs_table jt
LEFT JOIN applications_table at ON jt.jt_id = at.job_id AND jt.user_id = at.applicant_id
WHERE jt.visibility = 2 AND (jt.job_title LIKE :job_title) AND (jt.location = :location) AND (jt.salary >= :salary);
This should return all rows from jobs_table which match searched criteria and some of those rows can have extra data from applications_table if user already applied to that specific job (row) from jobs_table.
Something like:
jt_id user_id job_title location ... id applicant_id job_id
=================================================================
1 15 php dev london
2 23 java dev liverpool
3 44 haskell manchester
4 52 front end bristol 7 52 4
5 66 golang leeds
Row with jt_id = 4 has some extra values meaning user already applied to that job.
This should give you some directions but unfortunatelly, i didn't have a time to test this query.
EDIT
I've made a mistake. LEFT JOIN should go before WHERE clause...silly me. Check the query once again, it has been updated.
Or try it online
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);
}
}
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.
I am setting a variable that contains an array as a constraint to a SELECT sql statement. However the constraint seems only to apply to one piece of data in the array. Why is this?
Code below:
<?php
include 'connection.php';
$Date = $_POST['date'];
$Unavail = 0;
$Avail = 0;
$Availid = 0;
$low = 99999;
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
while($request = mysql_fetch_array($dayresult)) {
$Unavail = $request;
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance WHERE Username != '$Unavail[username]'";
$dayresult1 = mysql_query($query1);
while($request1 = mysql_fetch_array($dayresult1)) {
echo "<span>" . $request1['name'] . " is available.</br>";
if ($request1['work_stats']<=$low) {
$low = $request1['work_stats'];
$Availid = $request1['name'];
}}
echo "<span>" . $Availid . " is available on " . $_POST['date'] . " and is on workstat level " . $low . ".</span></br>";
?>
The output shows two names in the first echo but then shows one of those names as available in the second echo (these echos are only in place as part of my testing),
Many Thanks
The first query can have multiple results.
SELECT username FROM daysoff WHERE date = '$Date'
Let's say if gives two rows: Dave and John.
You're only keeping the last record so it will seem like Dave is available.
You should probably do something like:
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
$unavailable_users = array();
while($request = mysql_fetch_array($dayresult)) {
$unavailable_users[] = $request["username"];
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance
WHERE NOT Username IN ('" . implode("','", $unavailable_users) . "')";
// etc
Or in one go with a LEFT JOIN:
SELECT `Username`, `name`, `work_stats`
FROM `freelance`
LEFT JOIN `daysoff` ON `freelance`.`Username` = `daysoff`.`username`
AND `daysoff`.`date` = '$Date'
WHERE
`daysoff`.`username` IS NULL
My desired result is to display how many times each video (title) was watched for specific dates, by grabbing all of the titles that appear in the table, and count how many times that title is recorded for specific years / months.
It is working, however, it is not displaying correctly.
Instead of
TITLE A - 2
TITLE B - 6
TITLE C - 4
TITLE D - 0
...
It is displaying like this
TITLE A - 2
- 6
- 4
TITLE BTITLECTITLED
my code:
//get report
if ($_GET['report'] == "custom") { //custom date report
$month = $_GET['month'];
$year = $_GET['year'];
$result2 = mysql_query("SELECT DISTINCT title AS displaytitle
FROM user_history GROUP by title");
if ($_GET['month'] == "") {
$result = mysql_query("SELECT title, COUNT(id) FROM user_history
WHERE year(date) = '$year' GROUP BY title");
} else {
$result = mysql_query("SELECT title, COUNT(id) FROM user_history
WHERE year(date) = '$year' AND month(date) = '$month' GROUP BY title");
}
while($row2 = mysql_fetch_array($result2)) {
$new_title = $row2['displaytitle'];
echo $row2['displaytitle'];
while($row = mysql_fetch_array($result)) {
echo ' - ' . $row['COUNT(id)'] . '<br />';
}
}
Can anyone offer a solution so that a count will display next to the title? Thanks!
Your code to display the title is outside the loop. If you want the title to be printed next to every value, put it inside the loop printing every value.
if ($_GET['report'] == "custom") { //custom date report
$sql = "
SELECT
titles.title,
COUNT(DISTINCT history.id) AS `count`
FROM
user_history titles
LEFT OUTER JOIN
user_history history
ON
titles.title = history.title
";
if (!empty($_GET['month']) && !empty($_GET['year'])) {
$sql .= "AND YEAR(history.date) = " . (int)$_GET['year'] . " AND MONTH(history.date) = " . (int)$_GET['month'];
} else if (!empty($_GET['year'])) {
$sql .= "AND YEAR(history.date) = " . (int)$_GET['year'];
}
$sql .= "
GROUP BY
titles.title
ORDER BY
titles.title
";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['title'] . ' - ' . $row['count'] . '<br />';
}
}