简体   繁体   English

如何循环数字数据库表,直到你有一个输入数字的总和php / sql

[英]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 id :: name :: numbers
1 ::: Jack ::::::: 4 1 :::杰克::::::: 4
2 : Katrina ::::: 2 2:卡特里娜::::: 2
3 :: Clyde :::::: 8 3 ::克莱德:::::: 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. 因此,如果输入为3,则输出带Jack的行,如果输入为5或6则输出Katrina,如果输入为7-14,则输出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 使用自联接来查找id等于或小于当前人的人数的总和

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: 上面的SQL会产生这样的结果:

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 然后,您可以遍历结果,检查输入与总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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