简体   繁体   中英

Getting multiple row and store to a variable. Mysql and php

I am creating an average kilometer run calculator for my system. So I am trying to get the last two date and last two run on my database.

This is my current code:

<?php

$conn = mysqli_connect('localhost','root','','mypms');

 $sqldates = "SELECT dateinput FROM sched ORDER BY dateinput DESC LIMIT 2";
 $sqlrun = "SELECT reading FROM sched ORDER BY reading DESC LIMIT 2"; 

 $resultdate = mysql_query($conn,$sqldates);
 $resultrun = mysql_query($conn,$sqlrun);


 while($rowdate = mysql_fetch_assoc($resultdate))
 {
     this ->
 }

 $date_difference = $date2 - $date1;

 while($rowrun = mysql_fetch_assoc($resultrun))
 {
     this ->
 }

 $run_difference = $run2 - $run1;
 $averagerun = $run_difference/$date_difference

 echo $averagerun;
?>

what should I write on my this so I can store my $resultrun and $resultdate to $date1, $date2 and $run1, $run2.

Note: Datetype of dateinput is date on my mysqldatabase.

Try this query instead - it will return your result

SELECT 
run_difference/date_difference AS averagerun
FROM
    (
        SELECT
        DATEDIFF(date2,date1) AS date_difference,
        reading2 - reading1 AS run_difference
        FROM
        (
            SELECT 
            (SELECT dateinput FROM sched ORDER BY dateinput LIMIT 0, 1) AS date1, 
            (SELECT dateinput FROM sched ORDER BY dateinput LIMIT 1, 1) AS date2,
            (SELECT reading FROM sched ORDER BY reading DESC LIMIT 0, 1) AS reading1,
            (SELECT reading FROM sched ORDER BY reading DESC LIMIT 1, 1) AS reading2 
            FROM DUAL
        ) t1
    )t2

or "one liner":

SELECT 
    (SELECT reading FROM sched ORDER BY reading DESC LIMIT 1, 1)-(SELECT reading FROM sched ORDER BY reading DESC LIMIT 0, 1)   /   DATEDIFF((SELECT dateinput FROM sched ORDER BY dateinput LIMIT 1, 1), (SELECT dateinput FROM sched ORDER BY dateinput LIMIT 0, 1))  AS averagerun
FROM DUAL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM