简体   繁体   中英

how to loop through a database table of numbers until you have sum of an input number php/sql

So basically if you have a table in your database which looks like this:

id :: name :: numbers
1 ::: Jack ::::::: 4
2 : Katrina ::::: 2
3 :: Clyde :::::: 8

I am looking to loop through the numbers column adding the numbers to each other until it reaches a certain number input and then echos out the one row, where the numbers has added up to. So if your input is 3 it will output the row with Jack, if the input is 5 or 6 it will output Katrina and if the input is from 7-14 it will output the row with clyde.
The thing here I cannot figure out is how i loop through the numbers column adding up the numbers until you reach a specific row, then to echo only that specific row out.

I know how to echo out all rows and creating the condition for the input field but I seem to be stuck at grasping how to go further.

    $sql = "SELECT medlemsid, navn, lotterinr, tid FROM medlemmer";
    $result = $con->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "| id: " . $row["medlemsid"]. " | - Name: " . $row["navn"]. " " ." | Lotterinr " . $row["lotterinr"]. " | Tid: ". $row["tid"]. "<br>";
    }
} else {
    echo "0 results";
}

if (isset($_POST['numberinput'])) {

            $numbers = $_POST['numberinput'];       

}

$con->close();
?>

<div id="udlodning-wrapper">

    <form name="login-form" class="login-form" method="post">

        <div>
            <input name="numberinput" type="number" id="numberinput"  placeholder="Lotterinummer" />
        </div>
        <div>
            <input type="submit" name="submit" value="Udlodning" id="udlodning-submit" class="button-input"/><br/>
        </div>
    </form>

</div>

Use self join to find out sum of number of people with id equal or less than current person

select
  p1.id,
  p1.name, 
  p1.number, 
  sum(p2.number) as sum
from people p1
join people p2 on p2.id <= p1.id
group by p1.id, p1.name, p1.number;

SQL above would produce a result like this:

id  name    number  sum
1   jack    4       4
2   katrina 2       6
3   clyde   8       14

You can then iterate through the result, checking your input against sum

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