Check if last 10 rows duplicated - php

I'm trying to code a php script, which can find if the last 10 rows from mySQL database are the same. And if the values are same, then the script could sent an email.
I can fetch the last 10 rows.
$sql = ("SELECT ID, DayTime,Temperature FROM AllinOne ORDER BY ID DESC LIMIT 10");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["ID"]. " - DayTime: " . $row["DayTime"]. " - Temperature " . $row["Temperature"]. "<br>";
}
} else {
echo "0 results";
}
Last 10 results:
Now, I'm trying to check if last 10 rows in "Temperature" column are the same (as we can see).
I use:
$sql2 = "SELECT Temperature, COUNT(*) as duplicates FROM AllinOne GROUP BY Temperature ORDER BY ID DESC LIMIT 10";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0)
{
// output data of each row
while($row2 = $result2->fetch_assoc())
{
echo $row2["duplicates"]. "<br>";
}
}
but I can't take back the same results (i can't understand the final result).
$row2 results
Could you help me???

Execute the following query and grab the result:
SELECT
COUNT(*) AS count_rows,
MIN(Temperature) AS min_temperature,
MAX(Temperature) AS max_temperature
FROM (
SELECT *
FROM t
ORDER BY DayTime DESC
LIMIT 10
) AS x
Then send an email if count_rows = 10 and min_temperature = max_temperature.

You just need to fix your second query like:
$sql2 = "SELECT Temperature, COUNT(*) as duplicates
FROM (
SELECT ID, DayTime, Temperature FROM AllinOne ORDER BY ID DESC LIMIT 10
) LastData
GROUP BY Temperature";
Here you can test PHP code with queries

Related

echoing an AVG value from a virtual value with mysql and php

I have the following query and it gives me the percentage. It works great and i echo it in a table. In this table i also want to echo the AVG % as a total.i.e i have 12 months of year and want the avg. % for the year at the bottom of the table. I have worked out how to do this for valuations and instructions that are stored in my database. But.. how do i do this for a 'virtual' column like %..as this has been created from a query and not a physical column in the database.
iam starting to think i need to combine the total valuations by total instructions to get my %. Any ideas how i can do this?
$query= "SELECT *,
concat(round(( instructions/valuations * 100 ),0),'%') AS percentage
FROM office_figures2016";
$result = mysqli_query($conn, $query);
while($office_figures2016=mysqli_fetch_assoc($result)){
it echos :
echo"".$office_figures2016['percentage']."";
and here is the php to get the totals for each column...the third part of code is wrong but this is what i have so far:
<?php
$sql = "SELECT ROUND(AVG(valuations),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
$sql = "SELECT ROUND(AVG(instructions),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
// need to divide total valuations by total instructions x 100 = %
// somehow need to combine the value sums together.. if?
$sql = "SELECT ROUND(AVG(''),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";
I redid the formula to divide all instructions and valuations in the table x100 = %.
$sql = "SELECT ROUND(AVG(instructions / valuations *100 ),0) AS value_sum FROM office_figures2016";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td> " . $row["value_sum"]."</td>";

Getting Mysql $Row and query

i have made this code to get the top 5 songs views:
$mysqli_query ="SELECT page, count( * ) AS 'Cnt'
FROM pageview
GROUP BY page
ORDER BY `Cnt` DESC
LIMIT 5 ";
$result = mysqli_query($conn, $mysqli_query) or die (mysqli_error($conn));
$num_rows = mysqli_num_rows($result);
echo "<br>Top 5 Song views:<br>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " " .$row["page"]."<br />";
}
} else {
echo "0 results";
}
//fim
mysqli_close($conn);
?>
And it is working, but the $row["id"] is missing, in my mind i have to make another query, my question is can i join this in the existing query?
maybe you should do this
$mysqli_query ="SELECT id,page, count( * ) AS 'Cnt'
FROM pageview
GROUP BY page
ORDER BY `Cnt` DESC
LIMIT 5 ";

Sort query by time and list next entries

I'm trying to sort this query by time.
I have a gaming match system. And I want to get a list of next 5 matches from my local time zone.
<?php
include_once "include/dbcompo.php";
$q=mysqli_query($con, "SELECT * FROM kamper ORDER BY tid LIMIT 5");
while($row = mysqli_fetch_array($q))
{
$clan1 = $row['clan1'];
$clan2 = $row['clan2'];
$server = $row['server'];
$tid = $row['tid'];
echo $clan1." ".$clan2." ".$server." ".$tid;
echo "<br />";
}
?>
Add a WHERE clause in your query: WHERE tid > NOW().
With NOW() you take the time of the server, maybe you should replace it with new DateTime(null)->getTimestamp()
Something like that:
<?php
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > NOW() ORDER BY tid LIMIT 5');
// or
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > '.new DateTime(null)->getTimestamp().' ORDER BY tid LIMIT 5');
?>
Two options:
1st option: Make the time field a numeric field and sort in PHP:
$queryResult = mysqli_query($con, $query);
while($row = mysqli_fetch_array($queryResult) {
$oldArray[$row['time'] = $row;
}
$array = ksort($oldArray);
foreach($array as $time=>$row) {
// do something
}
2nd option: Make a subquery
SELECT * FROM (
SELECT * FROM kamper WHERE timezone = 'UTC' ORDER BY tid
) LIMIT 5

How can I optimise this mysql/php query?

My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.

MySQL show results with inverted order?

I need to get the last 5 results, that's why I order them by Date DESC but I need to display the results from older to newer. How can I do this?
$data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 5");
while($row = mysql_fetch_array( $data ))
{
print "<img class='badge' title='" . $row['Site'] . "' src='http://getfavicon.appspot.com/http://" . $row['Site'] . "?defaulticon=1pxgif' />";
}
$results = array();
while($row = mysql_fetch_array($data)) {
$results[] = $row;
}
$results = array_reverse($results);
foreach ($results as $row) {
echo $row['Site']; // etc
}
Manual link: http://php.net/function.array-reverse.php
$data = mysql_query("
SELECT * FROM (
SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 5)
t ORDER BY Date
");
Also:
Please use mysql_real_escape_string (http://at2.php.net/manual/en/function.mysql-real-escape-string.php) for the variable $user. Depending on where you get that from it could be a security leak through sql injection.
You can actually order a second time in the same query.
I assume that you have an auto incrementad id (I'll call it 'EntryId' in this example) and then you hopefully should get what you need?
SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC, EntryId ASC LIMIT 5

Categories