Latest by current date - php

I need help with an query. It is to list only 3 dog shows, by the row postal_date. However, I do not want any results that are past the current date.
I have them listed but some do show past the current date.
<?php
$query = "SELECT shows.*, judges.* FROM `shows`
INNER JOIN `judges` ON shows.judge_id = judges.judge_id
ORDER BY shows.postal_close DESC
LIMIT 3";
$select_all_shows_query = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_all_shows_query)) {
$show_id = $row['show_id'];
$show_title = $row['show_title'];
$postal_close = date('d F Y', strtotime($row['postal_close']));
$show_image = $row['show_image'];
$judge_name2 = $row['judge_name2'];
$judge_id = $row['judge_id'];
?>

$query = "SELECT shows.*, judges.* FROM `shows`
INNER JOIN `judges` ON shows.judge_id = judges.judge_id
WHERE DATE(shows.postal_close) >= CURDATE()
ORDER BY shows.postal_close DESC LIMIT 3";

Related

How to match two table columns in sql

I have this code
$db = \Config\Database::connect();
$query = $db->query("select * from g WHERE g_status = '0' ORDER BY g_date ASC Limit 10;");
foreach ($query->getResult() as $g) {
$g_amount = $g->g_amount;
}
$query2 = $db->query("select * from g WHERE p_status = '0' ORDER BY p_date ASC Limit 10;");
foreach ($query2->getResult() as $p) {
$p_amount = $p->p_amount;
}
if($p_amount == $g_amount){
echo "do something";
}else{
echo "No match";
}
Here I am trying to match between table g and table p.... if any column in table g is == any column in table p regardless of the number of column, do something but it always echo "NO match"
I put "Limit 10" in case there is much number of rows in the table, it will only match the first 10th row with the "ordering" command.
Please I need some help.
First, get data as an array
$db = \Config\Database::connect();
$query = $db->query("select * from g WHERE g_status = '0' ORDER BY g_date ASC Limit 10;");
$g_results = $query->getResult('array');
$g_amounts = array_column($g_results,'g_amount');
$query2 = $db->query("select * from g WHERE p_status = '0' ORDER BY p_date ASC Limit 10;");
$p_results = $query2->getResult('array');
$p_amounts = array_column($p_results,'p_amount');
foreach(array_intersect($g_amounts,$p_amounts) as $amount){
echo "do something";
}
Why not use a JOIN and see if it returns something? Not sure if my syntax is correct, I don't do JOINs very often:
SELECT * FROM g g_table JOIN p p_table ON g_table.g_amount = p_table.p_amount WHERE g_table.status = '0' AND p_table.status = '0'

How to conditionally run PHP code only when query returns results?

I hope someone can help me with the best way to structure this code.
I run an oil club as a volunteer and if there are no quotes for a specific oil type, then the page fails due to empty variables being used in queries further down the code.
Ideally I would like to default to $win_supplier_red_id = 0 if the query returns no results, but I'm not sure the best way to catch it and where is the best place in the code.
$sql2a= "Select Quote_id from tbl_quote where (select min(quote_price) as best_red from tbl_quote where fuel_type_id =2 AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ) AND quote_price > 10) = quote_price AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ) Order by timestamp Limit 1";
$stmt2a = $db->prepare($sql2a);
$stmt2a->execute();
$res2a = $stmt2a->fetchObject();
$best_red_quote = $res2a->Quote_id;
$sql2= "SELECT qt.quote_id, ft.fuel_type_id, ft.fuel_name, st.supplier_id, st.company_name as company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id, min( qt.quote_price ) AS best_red
FROM tbl_quote qt
INNER JOIN `tbl_suppliers` st ON qt.supplier_id = st.supplier_id
INNER JOIN `tbl_fuel-type` ft ON qt.fuel_type_id = ft.fuel_type_id
WHERE qt.Quote_id = $best_red_quote
Order by timestamp";
$stmt2 = $db->prepare($sql2);
$stmt2->execute();
$res2 = $stmt2->fetchObject();
$best_red = $res2->best_red;
$winning_supplier_red = $res2->company_name;
$win_supplier_red_id = $res2->supplier_id;
$stmt2 = $db->prepare($sql2);
$stmt2->execute();
$res2 = $stmt2->fetchObject();
if (is_object($res2)) {
$best_red = $res2->best_red;
$winning_supplier_red = $res2->company_name;
$win_supplier_red_id = isset($res2->supplier_id) ? $res2->supplier_id : 0;
} else {
$best_red = '';
$winning_supplier_red = '';
$win_supplier_red_id = 0;
}

mySQL Order by Most Commented and Least Commented

I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";

Query to get top 5 users by total month sales amount

I was hoping you could help me figure this out. I would like to run a query that would search a table and all it's rows and the date matches the current month. Then return the user_id. What I am trying to achieve is gathering the top 5 user id's under this query.
How can I change this to find the top 5 for the current month? I am usually able to figure out my queries but this one has me stumped.
This is all I have at the moment.
$top = mysqli_query($mysqli, "SELECT sum(amount) AS total FROM sales WHERE status = 'S' AND MONTH(date) = 1");
while($row = mysqli_fetch_row($top))
{
$userid = $row['0'];
}
Update:
$top = mysqli_query($mysqli, "SELECT user_id
FROM
(
SELECT user_id, SUM(amount) total
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
) q
ORDER BY total DESC
LIMIT 5");
while($row = mysqli_fetch_row($top))
{
$topsales[] = $row['0'];
}
foreach($topsales as $topsale) {
echo $topsale;
}
Are you looking for a query like this?
SELECT user_id
FROM
(
SELECT user_id, SUM(amount) total
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
) q
ORDER BY total DESC
LIMIT 5
or just
SELECT user_id
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
ORDER BY SUM(amount) DESC
LIMIT 5
Here is SLQFiddle demo
Note: using MONTH() and YEAR() functions will prevent MySql from using any index you might have on date column
Now your php code might look like this
$db = new mysqli('localhost', 'user', 'password', 'dbname');
if ($db->connect_errno) {
die('Cannot connect'); // TODO: better error handling
}
$sql = "SELECT user_id
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
ORDER BY SUM(amount) DESC
LIMIT 5";
$topsales = array();
if ($query = $db->prepare($sql)) {
$query->execute();
$query->bind_result($user_id);
while ($query->fetch()) {
$topsales[] = $user_id;
}
$query->close();
} else {
die('Unable to prepare: ' . $db->error); // TODO: better error handling
}
$db->close();
foreach ($topsales as $topsale) {
echo $topsale . '<br>';
}

Sort the results of a query using results of another query

Im working on a message board of some sort and i have everything up an running except one little part, the threads need to be sorted by the date/time of the latest post in them (standard forum format), which im having lots of trouble wrapping my head around.
This is the querys im using, i know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
$sql = "SELECT Thread_ID, Thread_Title, Board_ID, Author FROM threads WHERE Board_ID='$Board_ID' LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$getauthor = mysql_query("SELECT * FROM members WHERE Member_ID='$Author'");
while ($row = mysql_fetch_assoc($getauthor))
{
$Post_Author = $row['Post_As']; }
$postcount = mysql_query("SELECT Post_ID FROM posts WHERE Thread_ID='$Thread_ID'");
$Posts = mysql_num_rows($postcount);
$getlatest = mysql_query("SELECT * FROM posts WHERE Thread_ID='$Thread_ID' ORDER by Post_DateTime DESC LIMIT 1");
while ($row = mysql_fetch_assoc($getlatest))
{
$Post_DateTime = time_ago($row['Post_DateTime']);
$Member_ID = $row['Member_ID']; }
$getmember = mysql_query("SELECT * FROM members WHERE Member_ID='$Member_ID'");
while ($row = mysql_fetch_assoc($getmember))
{
$Post_As = $row['Post_As']; }
So what im trying to do is Sort $sql by $getlatest, i tried adding another query above $sql that did basically the same as $getlatest and then had $sql order by that but alas it just broke everything.
I know i have to make a variable to sort the $sql by but its that variable thats driving me mad.
any help would be appreciated, thanks.
current error message as requested:
Fatal error: SQL - Unknown column 'posts2.LatestPost' in 'on clause' - SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs FROM threads INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1 ON threads.Thread_ID = Sub1.Thread_ID INNER JOIN members ON threads.Author = members.Member_ID INNER JOIN posts posts2 ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.LatestPost INNER JOIN members members2 ON members2.Member_ID = posts2.Member_ID WHERE threads.Board_ID='1' ORDER BY Sub1.LatestPost DESC LIMIT 0, 25 in C:\wamp\www\forum\include\threads.php on line 86
You should be able to do it using something like this for your first query:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, MAX(posts.Post_DateTime) AS LatestPost
FROM threads
LEFT OUTER JOIN posts ON threads.Thread_ID = posts.Thread_ID
WHERE threads.Board_ID='$Board_ID'
GROUP BY SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author
ORDER BY LatestPost DESC
LIMIT $offset, $rowsperpage";
EDIT
Not tested the following but looking at your selects I think you could probably put it together into a single SELECT. Something like this:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs
FROM threads
INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1
ON threads.Thread_ID = Sub1.Thread_ID
INNER JOIN members
ON threads.Author = members.Member_ID
INNER JOIN posts posts2
ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.Post_DateTime = Sub1.LatestPost
INNER JOIN members members2
ON members2.Member_ID = posts2.Member_ID
WHERE threads.Board_ID='$Board_ID'
ORDER BY Sub1.LatestPost DESC
LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$Post_Author = $row['Post_As'];
$Posts = $row['PostCount'];
$Post_DateTime = time_ago($row['LatestPost']);
$Member_ID = $row['LastPostMemberID'];
$Post_As = $row['LastPostMemberPostAs'];

Categories