I am wondering if it is possible to compare dates in all $row's from a while loop to today's date. Let me explain.
I have created this table shown in this image:
I have created this table through joining several tables, and actually have a while loop inside a while loop (which is how I got multiple games to show on one row, but only one wager amount per row.
What I want to do is compare the dates of each of the individual games to today's date, to list if the parlay is active or not (in this image, they would all not be active, but that's not the point).
I want to take today's date and if it is less than all the dates of the games, then Active == 'Future', or if today's date is in between a set of dates, then Active == 'In Progress', and if today's date is past all the dates, then Active == 'Past'. One part that makes this challenging is that I do not know how many individual games there will be, so I'm thinking something like this may work:
/* fetch row */
$firstrow = $result2->fetch_row();
$date1=date_create("$firstrow[0]");
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
But I don't know how many rows to make to test my last date, perhaps something with a
$row_count = $result->num_rows;
$datelast=date_create("$lastrow[$row-count-1]");
Not sure how to then implement and use this if it is the correct logic!
So does anyone know how I can compare each of these date rows to today's current date?
This is my initial select query:
I've omitted some info from my image, to try to make the core logic of the problem easier, that's why there are some extra fields here
//Create parlay select query
$query = "SELECT
u.first_name AS 'User First Name',
u.last_name AS 'User Last Name',
b.betting_site_name AS 'Betting Site',
p.id AS 'Parlay ID',
p.wager AS 'Wager',
p.odds AS 'Odds',
p.success AS 'Success',
DATE_FORMAT(p.creationdate, '%d-%m-%Y') AS 'Date',
pg.parlayid AS 'PG Parlay ID',
SUM(p.wager * p.odds) AS Winnings
FROM parlays p
JOIN parlaygames pg ON pg.parlayid = p.id
JOIN bonuses b ON p.bettingsiteid = b.id
JOIN users u ON p.userid = u.id
WHERE userid=$id
GROUP BY p.id
ORDER BY p.id DESC
LIMIT 5";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
This is my table creation code (and second while loop to get the individual games):
<h2>Betting History</h2>
<table class="table table-striped userwinnings">
<tr>
<th>Parlay Information</th>
<th>Wager</th>
<th>Active</th>
</tr>
<?php
while($row = $result->fetch_assoc()) {
$output = '<tr>';
$output .= '<td><table><tr><th>Date</th><th>Game</th><th>Bet Info</th></tr>';
$parlayid = $row['Parlay ID'];
$query3 = "SELECT
pg.parlayid AS ParlayID,
g.date AS GameDate,
ht.name AS HomeTeam,
away.name AS AwayTeam,
pg.betinfo AS BetInfo
FROM parlaygames pg
JOIN parlays p ON pg.parlayid = p.id
JOIN games g ON pg.gameid = g.id
JOIN teams ht ON g.home_team = ht.id
JOIN teams away ON g.away_team = away.id
JOIN users u ON u.id = p.userid
WHERE p.id = $parlayid";
$result3 = $mysqli->query($query3) or die($mysqli->error.__LINE__);
while($row3 = $result3->fetch_assoc()) {
$gamescount = $result3->num_rows;
$output .= '<tr>';
$output .= '<td>'.$row3['GameDate'].'</td>';
$output .= '<td>'.$row3['HomeTeam'].' vs '.$row3['AwayTeam'].'</td>';
$output .= '<td>'.$row3['BetInfo'].'</td>';
$output .= '</tr>';
}
$output .= '</table>';
$output .= '</td>';
$output .= '<td>'.$row['Wager'].'</td>';
$output .= '<td>'.$row['Active'].'</td>';
$output .= '</tr>';
echo $output;
}
?>
</table>
Hi please replace these query
$query3 = "SELECT
pg.parlayid AS ParlayID,
g.date AS GameDate,
ht.name AS HomeTeam,
away.name AS AwayTeam,
pg.betinfo AS BetInfo
FROM parlaygames pg
JOIN parlays p ON pg.parlayid = p.id
JOIN games g ON pg.gameid = g.id
JOIN teams ht ON g.home_team = ht.id
JOIN teams away ON g.away_team = away.id
JOIN users u ON u.id = p.userid
WHERE p.id = $parlayid";
With these one
$query3 = "SELECT
pg.parlayid AS ParlayID,
g.date AS GameDate,
IF((NOW() between MIN(g.date) AND MAX(g.date)),'In Progress',IF((MAX(g.date) > NOW()),'Future','Past')) as Acctive,
ht.name AS HomeTeam,
away.name AS AwayTeam,
pg.betinfo AS BetInfo
FROM parlaygames pg
JOIN parlays p ON pg.parlayid = p.id
JOIN games g ON pg.gameid = g.id
JOIN teams ht ON g.home_team = ht.id
JOIN teams away ON g.away_team = away.id
JOIN users u ON u.id = p.userid
WHERE p.id = $parlayid group by pg.parlayid";
This is how I ended up solving this issue:
while($row3 = $result3->fetch_assoc()) {
$gamescount = $result3->num_rows;
/* seek to row no. 1 */
$result4->data_seek(0);
/* fetch row */
$firstrow = $result4->fetch_row();
$result4->data_seek($gamescount-1);
$lastrow = $result4->fetch_row();
$date1=date_create("$firstrow[1]");
$date3=date_create("$lastrow[1]");
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date3,$date2);
$firstdate = $date3->format('Y-m-d');
$lastdate = $date1->format('Y-m-d');
$today = $date2->format('Y-m-d');
if ($firstdate < $today && $today < $lastdate) {
$active = "In Progress";
} else if ($today > $lastdate) {
$active = "Past";
} else if ($today < $firstdate) {
$active = "Future";
}
I hope this logic can help others as well.
Related
I have a page of categories, they worked fine until I did a join.
The categories display like so:
category 1-----------------------0----------0
discussion 1 by someone
category 2-----------------------0----------0
discussion 2 by someoneelse
Now where it says discussion, I need to display the last discussion posted to that category based on it's discussion_id. I have tried ORDER BY ... DESC but it sorts by category names not the discussion names and posted by.
$sql = "SELECT *, COUNT(d.cat_id) as count
FROM discussions as d
LEFT JOIN categories c ON (c.cat_id = d.cat_id)
RIGHT JOIN soldiers s ON (s.uid = d.discussion_poster)
GROUP BY d.cat_id";
$result = query($sql);
while (($row = mysqli_fetch_assoc($result)) != false) {
$cat_id = $row['cat_id'];
$discussion_id = $row['discussion_id'];
$cat_title = $row['cat_title'];
$discussion_title = $row['discussion_title'];
$discussion_time = $row['discussion_time'];
$count = $row['count'];
$discussion_poster_id = $row['discussion_poster'];
$discussion_poster = $row['soldier'];
}
$sql = "
SELECT *
FROM categories c
INNER JOIN
(
SELECT MAX(discussion_id) discussion_id,
COUNT(discussion_id) as count,
cat_id
FROM
discussions
GROUP BY
cat_id
) as d1
ON (c.cat_id = d1.cat_id)
INNER JOIN discussions as d
ON (d1.discussion_id = d.discussion_id)
INNER JOIN soldiers s
ON (s.uid = d.discussion_poster)
GROUP BY d.cat_id";
For some reason the member id field(auto inc.) in my huge query is returning null.I've tried every which way of selecting it... m.member_id AS member_id, etc.I cannot figure out why it is returning null when there is a value for that field in the table.
<?php
public function get_info($criteria = 0){
if(is_numeric($criteria)){
$where = "WHERE m.member_id = ".$criteria;
} else {
$where = "WHERE email_address = '".$criteria."'";
}
$query_member = "
SELECT
m.member_id AS member_id, m.display_name, m.email_address, m.group_id, m.status, m.activation_code, UNIX_TIMESTAMP(m.date_joined) AS date_joined,
m.gender, m.location, m.biography, m.mantra, m.birth_date, m.results_per_page, m.admin_emails, m.member_emails, m.last_active, m.avatar_id,
m.banner_id, m.signature, m.newsletter_subscription, m.recruiting_status, m.facebook_username, m.website, m.steam_username, m.xboxlive_gamertag, m.psn_id,
g.group_id, g.title, g.description,
a.attachment_id, a.file_name,
f.message_id, f.author_id, COUNT(f.message_id) AS forum_count,
b.attachment_id AS banner_id, b.file_name AS banner_file,
mr.request_id, mr.author_id, mr.recipient_id, mr.status, COUNT(mr.request_id) AS total_friends,
tm.team_member_id, tm.member_id, tm.team_id
FROM members AS m
LEFT JOIN member_groups AS g ON (m.group_id = g.group_id)
LEFT JOIN attachments AS a ON (m.avatar_id = a.attachment_id)
LEFT JOIN forum_messages AS f ON (m.member_id = f.author_id)
LEFT JOIN attachments AS b ON (m.banner_id = b.attachment_id)
LEFT JOIN member_requests AS mr ON (m.member_id = mr.author_id OR m.member_id = mr.recipient_id) AND mr.status = 1
LEFT JOIN team_members AS tm ON (m.member_id = tm.member_id) AND date_left = ''
".$where."
GROUP BY m.member_id
LIMIT 1";
//show_error($query_member);
if($query_member = $this->db->query($query_member)){
if($query_member->num_rows() > 0){
var_dump($query_member->row_array());
Because you select two fields with the same name. So MySQL will return result of last one. Add aliases:
SELECT m.member_id AS member_id_1, tm.member_id AS member_id_2 ...
I have a 4 table merge going on and in the end I want it to be sorted by an "ORDER BY" according to some variable. Right now this is always returning the same order of entries.
Something like:
if(isset($_GET['filter'])){
$filter = $_GET['filter'];
#Example $filter = 'date' or team or game_num
$q = $db->prepare("SELECT g.game_num, s.date, t.team
FROM schedule n
LEFT JOIN g_lkp g
ON n.game_num = g.game_num
LEFT JOIN dates s
ON n.date = s.date
LEFT JOIN teams t
ON n.home_team_nbr = t.team
ORDER BY '$filter' ");
$q->execute();
$qR = $q->fetchAll(PDO::FETCH_ASSOC);
if ($q->rowCount() > 0) {
foreach ($qR as $row) {
echo '
//First check value of $filter
$q = $db->prepare("SELECT g.game_num game_num, s.date date, t.team team
FROM schedule n
LEFT JOIN g_lkp g
ON n.game_num = g.game_num
LEFT JOIN dates s
ON n.date = s.date
LEFT JOIN teams t
ON n.home_team_nbr = t.team
ORDER BY $filter ");
I have a PHP script that loops through 2000+- records uisng a while loop. Within this while loop a postgres sql query has to be performed, unfortunately it can't be excluded from the while loop.
$sql = "(SELECT (timestamp) AS time FROM followups as f
JOIN campaigns as c ON c.id = f.campid
WHERE c.clientid = ".trim($clientid)." AND c.contractno = '".trim($c)."' AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (SELECT (timestamp) AS time FROM followups as f WHERE (contractno ='".trim($c)."'
OR contractno LIKE '%".trim($c)."||".trim($clientid)."%'
OR contractno = '".trim($c)."||".trim($clientid)."') AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (select (f.timestamp) AS time FROM followups as f
JOIN campaigns as c on c.id = f.campid WHERE c.clientid = ".trim($clientid)."
AND c.clientid in (
SELECT id FROM easy_mapping where id = ".trim($clientid).") AND (LOWER(person) IN (SELECT LOWER(userid)
FROM users WHERE type IN('S','X')) OR LOWER(person) IN
(SELECT LOWER(name) FROM users WHERE type IN('S','X'))))";
$result = pg_query($conn,$sql);
The query above is included in the while loop, the first few records perform very quickly and then the script starts to slow down, taking almost a day to complete the script. Is there a way to write the exact query above differently to gain the same results?
UPDATE:
Here's the complete loop
$dates = array();
$clientid = str_replace("\t", '', $clientid);
foreach ($contracts as $c) {
$c = str_replace("\t", '', $c);
$sql = "(SELECT MAX(timestamp) AS time FROM followups as f
JOIN campaigns as c ON c.id = f.campid
WHERE c.clientid = ".trim($clientid)." AND c.contractno = '".trim($c)."' AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (SELECT MAX(timestamp) AS time FROM followups as f WHERE (contractno ='".trim($c)."'
OR contractno LIKE '%".trim($c)."||".trim($clientid)."%'
OR contractno = '".trim($c)."||".trim($clientid)."') AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (select MAX(f.timestamp) AS time FROM followups as f
JOIN campaigns as c on c.id = f.campid WHERE c.clientid = ".trim($clientid)."
AND c.clientid in ( SELECT id FROM easy_mapping where id = ".trim($clientid).") AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))))";
$result = pg_query($conn,$sql);
if (pg_num_rows($result)>0) {
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
if (empty($row['time'])) {
continue;
}
$dates[] = $row['time'];
}
}
pg_free_result($result);
}
if (empty($dates)) {
return false;
} else {
$max = max($dates);
if (strtotime(date("Y-m-d")) < strtotime(date("Y-m-t"))) {
$compdate = date("Y-m-01", strtotime("-1 month") );
} else {
$compdate = date("Y-m-01");
}
if (strtotime($compdate) > $max) {
return false;
} else {
return true;
}
}
unset($dates);
The following is the result of what I can understand from your really junkish code.
$clientid = trim(str_replace("\t", '', $clientid));
$sql = "
select max(time)
from (
(
select max(timestamp) as time
from
followups f
inner join
campaigns c on c.id = f.campid
inner join
users u on lower(f.person) in (lower(u.userid), lower(u.name))
where
c.clientid = $clientid
and u.type in('S','X')
)
union
(
select max(timestamp) as time
from
followups as f
inner join
users u on lower(f.person) in (lower(u.userid), lower(u.name))
where
contractno like ('%' || $clientid || '%')
and u.type in('S','X')
)
union
(
select max(f.timestamp) as time
from
followups as f
join
campaigns as c on c.id = f.campid
inner join
users u on lower(f.person) in (lower(u.userid), lower(u.name))
inner join
easy_mapping em on c.clientid = em.id
where
c.clientid = $clientid
and u.type in('S','X')
)) s
";
$result = pg_query($conn,$sql);
if (pg_num_rows($result) == 0) {
return false;
} else {
$max = $row['time'];
if (strtotime(date("Y-m-d")) < strtotime(date("Y-m-t"))) {
$compdate = date("Y-m-01", strtotime("-1 month") );
} else {
$compdate = date("Y-m-01");
}
if (strtotime($compdate) > $max) {
return false;
} else {
return true;
}
}
pg_free_result($result);
I'm using Wordpress and I have to figure out how to get multiple values out of the same column and turn them into variables.
The last step is I just want the data to display in a table like so:
Bob Company1 <br>
Alex Company2
Instead I get either Bob Alex Company1 Company 2 or
Bob <br>
Alex<br>
Company1<br>
Company2
Here's two different versions I'm working with:
$sql = "SELECT meta_value as guest from wp_postmeta INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id WHERE post_type='guests' AND meta_key='guest_name' UNION SELECT meta_value as company from wp_postmeta INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id WHERE post_type='guests' AND meta_key='guests_company'";
$result = mysql_query($sql);
$NumberOfResults=mysql_num_rows($result);
if (mysql_num_rows($result) == 0) {
echo "No Guests yet... stay tuned!";
exit;
}
while(list($guest,$company)= mysql_fetch_row($result))
{
echo "<table><tr><td>".$guest."</td><td>".$company."</td></tr></table>";
}
or
$sql = mysql_query("SELECT meta_value as guest from wp_postmeta INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id WHERE post_type='guests' AND meta_key='guest_name' LIMIT 2 UNION SELECT meta_value as company from wp_postmeta INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id WHERE post_type='guests' AND meta_key='guests_company'");
$i = 1;
while ($get = mysql_fetch_array($sql))
{
echo '<table><tr><td>'.$get["guest"].'</td><td>'.$get["company"].'</td></tr></table>';
$i++;
}
ANY HELP would be so appreciated!!! thanks!
Edit: In case anybody in the future wants to create their own widget using advanced custom fields in Wordpress, here's the final product more or less:
$sql = "SELECT p.ID AS post_id, g.meta_value as guest, c.meta_value as company, d.meta_value as date
FROM wp_posts p
JOIN wp_postmeta g ON g.post_id = p.id AND g.meta_key = 'guest_name'
JOIN wp_postmeta c ON c.post_id = p.id AND c.meta_key = 'guests_company'
JOIN wp_postmeta d ON d.post_id = p.id AND d.meta_key = 'show_date'
WHERE p.post_status = 'publish'
ORDER by d.meta_value DESC";
$query = mysql_query($sql);
echo '<table><tr><th>Guest</th><th>Company</th><th>Show Date</th></tr>';
while ($get = mysql_fetch_array($query)) {$newDate = date("m-d-Y", strtotime($get["date"]));
echo '<tr><td>'.$get["guest"].'</td><td>'.$get["company"].'</td><td>'.$newDate.'</td></tr>';
}
echo '</table>';
Really appreciated doublesharp's help on this.
If I understand your question correctly, you have to write the code to display table like this:
echo '<table>';
while ($get = mysql_fetch_array($sql))
{
echo '<tr><td>'.$get["guest"].'</td><td>'.$get["company"].'</td></tr>';
}
echo '</table>';
If the postmeta values are attached to different posts as indicated by the different 'post_type' values in your query, then you will need some other identifying information to link them together. If there is a single post_id that has both a guest_name and guest_company meta_value then you can join it twice to get the results. Using a UNION will always result in them coming back in different rows.
// Join the postmeta table to posts twice, once for each meta_key.
$sql = <<<SQL
SELECT p.ID AS post_id, g.meta_value as guest, c.meta_value as company
FROM wp_posts p
JOIN wp_postmeta g ON g.post_id = p.id AND g.meta_key = 'guest_name'
JOIN wp_postmeta c ON c.post_id = p.id AND c.meta_key = 'guests_company'
WHERE p.post_status = 'publish'
SQL;
// Execute the query
$query = mysql_query($sql);
// Start your table for output
echo '<table>';
while ($get = mysql_fetch_array($query)) {
// Write the output of each row
echo '<tr><td>'.$get["guest"].'</td><td>'.$get["company"].'</td></tr>';
}
// Close the table
echo '</table>';
If this is inside Wordpress, I would recommend using the $wpdb object for your query.