Get the minimum and maximum number in PHP from DB - php

I'm making a PHP code for showing data of my weather station.
I have a DB in MySQL with 5 columns.
This is my actual code:
<?php
$conexion=mysqli_connect('localhost','dbone','root','dbdata');
?>
<?php
$sql="SELECT * from Sensor ORDER BY id DESC LIMIT 1";
$result=mysqli_query($conexion,$sql);
date_default_timezone_set("Europe/Warsaw");
$calpres=57;
$caltemp=0;
$calhumi=0;
while($mostrar=mysqli_fetch_array($result)){
?>
<?php
?>
|esta=c00m000e00|data=<?php echo date("d-m-Y H:i:s"); ?>|temp=<?php echo $mostrar['value1'] - $caltemp ?>|hum=<?php echo $mostrar['value2'] ?>|pres=<?php echo $mostrar['value3'] + $calpres ?>
<?php
}
?>
The actual result is:
|esta=c00m000e00|data=24-01-2021 19:42:10|temp=10.71|hum=58.20|pres=1016.12
Value1 is the column that includes the temperature. I would like to show the maximum and minimum temperature, but I don't know how to do it.
Thank you very much!

You could use SQL MAX() and MIN() functions.
Something like SELECT MAX(value1) FROM Sensor

Either run 2 queries (one for min and one for max) like this:
(if your column name is temp)
SELECT * from Sensor ORDER BY temp DESC LIMIT 1
SELECT * from Sensor ORDER BY temp ASC LIMIT 1
and the take the first and only rows from them.
A little bit cleaner way is to take all the data you need, ordered by temp, (no LIMIT at the end)
SELECT * from Sensor ORDER BY temp DESC
fetch it in an array, and get the first tempArray[0] and the last tempArray[count(tempArray)-1] - values, they will containt min and max rows.
$result = mysql_query("SELECT * from Sensor ORDER BY temp DESC");
$sensorArray = []
while( $row = mysql_fetch_assoc( $result)){
$sensorArray[] = $row;
}
$max = $sensorArray[0];
$min = $sensorArray[count($sensorArray)-1];

Related

How to get the first ID with SQL

I am trying to get the first id with a specific date.
So this is my code:
$checkm = "SELECT FIRST(id) FROM times WHERE date='2014-03-07'";
$resultm = mysqli_query($con,$checkm);
I have a table called times and there are some columns. Two of them are date and id.
I am trying to get the first row's id with the date 2014-03-07.
EDIT: Fixed!
$checkm = "SELECT id FROM times WHERE date='2014-03-06' ORDER BY id ASC LIMIT 1";
$resultm = mysqli_query($con,$checkm);
while($row = mysqli_fetch_array($resultm)) {
$resultm1 = $row['id'];
}
You probably want the minimum id.
SELECT min(id)
FROM times
WHERE date = '2014-03-07'
pretty straightforward...
SELECT id FROM times WHERE date='2014-03-07' ORDER BY id ASC LIMIT 1

How to "shift" query result one row further

Let's say I have something like this:
$sql = $con->query("SELECT * FROM Content ORDER BY Time DESC LIMIT 2");
while ($row = $sql->fetch()) {
echo $row['title'];
}
So this grabs the 2 latest entries in a table and then echoes the designated column. How can I take the 2nd and 3rd most recent entries from my table ignoring the first one?
Right now I'm thinking about setting the limit to 3 and somehow skipping the first result and grabbing the 2 remaining.
Try this :
LIMIT 1,2
1 => offset : From where to start(First one will be 0)
2 => number of records
$sql = $con->query("SELECT * FROM Content ORDER BY Time DESC LIMIT 1,2");
while ($row = $sql->fetch()) {
echo $row['title'];
}

Count how many times a specific value is retrievied from a SQL QUERY

MySQL table: name, salary, childrens, brothers, age
I'm trying to retrieve the name of the person who has the max value in salary, childrens and brothers, with age>30. Note: every name is unique.
To do achieve this I loop through all columns whit this array:
$columns = array('salary','childrens','brothers')
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
echo $rows[name];
};
};
Everything works fine, but I would also like to count the amount of times each name is retrived (echoed).
i.e.: Max has the highest salary and the highest amount of brothers, so his name has been retrivied 2 times. Loren only has the highest amount of childrens, so his name has been retrivied 1 time. Jason has never been retrivied, so it's 0 for him.
I tried this:
$i=0;
$columns = array('salary','childrens','brothers')
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
echo "The person who has the max amount of $value is $rows[name]";
$count[$rows[name]] = $i++;
};
};
But it doesn't work as intended, it counting the number of times eache name appears in every columns without taking into account if it has the max value.
Any help would be appriciated.
ps: if you also can improve the code the retrivie the max value I would be grateful.
UPDATE:
The query for each table should output this:
Name salary
Max 2000
--
Name childrens
Loren 4
--
Name brothers
Max 3
The $count array should be:
$count = array('Max'=>2,'Loren'=>1,'Jason'=>0,'etc'=>0);
You used the same counter for all names. Try to split them. Something like that:
$count=array();
$columns = array('salary','childrens','brothers')
foreach($columns as $value) {
$result=mysql_query(
"SELECT `name`, `$value`
FROM table_name
WHERE `age`>30
ORDER BY `$value` ASC
LIMIT 1"
);
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "The person who has the max amount of $value is $rows[name]";
if(!isset($count[$rows[name]]))
$count[$rows[name]] = 0;
++$count[$rows[name]];
};
};
print_r($count);
UPD: And also if you need a row with MAX value, you must use DESC instead of ASC
UPD2: To retrieve all the users, you need also execute SELECT DISTINCT name FROM table_name before previous code and fetch it into array $count[$r['name']] = 0
I'm not sure what you up to , but in programing i will use comparing method to get highest value , but there is another MAX() function in server side language to get greatest value of all record http://www.w3schools.com/sql/sql_func_max.asp
$columns = array('salary','childrens','brothers');
$highest = array(array('salary'=>0,'childrens'=>0,'brothers'=>0));
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
//compare the value of each record if greater then replace
if($highest[$value]<$rows[$value]){
//replace with current highest value and set name into array
$highest[$value]=$rows[$value];
$highest[$value]=$rows[name];
}
};
};
print_r($highest);

SELECT * FROM table_name ORDER BY column_name?

ok so i coded in a news section and everytime i insert new news,its shows below the old one.
i want to make it ORDER BY id but make it start like backwards.i dont know how to explain but yeh
i want them to be ordered by the newest added by the id so if the 1st row that was inserted's id is 1 then i want it to show below the next id.
so row with id = 2 will be here
so row with id = 1 will be here
thats how i want it to be, instead of it being like this
so row with id = 1 will be here
so row with id = 2 will be here
.
Sorry for my bad explanation i hope this is understandable
heres my code so far
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>
add DESC in your ORDER BY clause
SELECT * FROM news ORDER BY id DESC
by default, it is in ASC mode.
SELECT * FROM news ORDER BY id DESC
DESC is the descending keyword ASC is ascending
If you specify neither then default behaviour is ascending
Just use DESC keyword in your sql query.
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
However, it isn't really such a good idea to use id, because semantically, there is nothing preventing somebody from changing the sequence which counts up automatically assigning the ID.
Therefore, you should add a column created_at. Everytime you insert a row, you can use the SQL function NOW().
The advantage is that you can say:
SELECT * FROM news WHERE created_at <= NOW() ORDER BY created_at DESC
This means that you can schedule news items ahead of time, and it will automatically display when the date/time arrives!
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
try this:
just have to add
order by id DESC
Just replace your code by this code:
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>

Ranking/numbering in php

I tried to achieve a method in which I create a scoreboard (while loop) and order the fetched results by a certain numeric field (points). But what I need to achieve is like the following
rank----username--point
1st------test-----------3200
2nd-----test2---------1200
etc.. I paginate my results and limit 25 results per page. I tried a while loop in the following way
while($row = mysql_fetch_array($query) || $i<=$totalnumberofrows ){
echo out the results
$i++
}
What this does is number from 1 to 25 perfectly, but on the other hand, on page 2 it numbers again from 1-25.
Is there a trick to achieve what I need to achieve?
I.e. continuous numbering from 1 to (total number of rows) even when paginated.
What you're looking for is the MySQL LIMIT statement. For example, the following query would return entry 0-24 (so, the first 25 entries in your database):
SELECT * FROM entries ORDER BY `points` LIMIT 0, 25
Say that you want to fetch the second page (the next 25 entries), you can do:
SELECT * FROM entries ORDER BY `points` LIMIT 25, 25
Most important thing to note here is that the first argument is the row where it should start, and the second argument is not the last row, but the total amount of rows it should return.
To determine the starting point, simply do (($page_number - 1) * 25), assuming your first page is numbered 1. You could for example do the following:
<?php
$start = (($page_number - 1) * 25);
$query = "SELECT * FROM entries ORDER BY `points` LIMIT {$start}, 25";
// ... rest of your code goes here ...
?>
just add 25 to the number for each page,
for the second page (in my example) - add 25
for the third page - add 50
etc...
$page = 2;
while($row = mysql_fetch_array($query) || $i<=$totalnumberofrows ){
echo out the results
echo (($page-1)*$totalnumberofrows)+$i;
$i++
}
If you know the page number and the offset you should be able to do the following
$rank = $offset * $page_number;

Categories