【发布时间】:2014-07-09 16:40:22
【问题描述】:
你能想象我的问题吗? ..例如我有无限碗。但是在一个碗里我只能拉出 3 个苹果。因此,如果有人给我 5 个苹果,我必须将 3 个苹果放入一个碗中,将 2 个放入第二个碗中。如果有人给我 7 个苹果,我把 3 个放在一个,3 个放在第二个,最后一个苹果放在一个碗里。
现在我尝试在 php 和 mysql 中进行此操作,苹果在 mysql 中作为变量和碗作为行。
if (isset($_POST[button])) {
$apples = $_POST["apples"];
$max_apples_in_bowl = 3;
//if apple variable is ≤ 3 it is OK so i can write into table
if ($apples <= 3) {
$query = "INSERT INTO `bowls` (`count_apples`) VALUES ('$apples');";
mysql_query($query);
}
//but if not - i have condition that include cycle which write into table value 3 and deducted from the apple value 3. This cycle continue until apples ≤ 3 and then write a reminding part into table
else {
while ($apples <= 3) {
$secondquery = "INSERT INTO `bowls` (`count_apples`) VALUES ('$max_apples_in_bowl');";
mysql_query($secondquery);
$apples = $apples - $max_apples_in_bowl;
$thirdquery = "INSERT INTO `bowls` (`count_apples`) VALUES ('$apples');";
mysql_query($thirdquery);
}
}
}
但这行不通。当然,如果我将 $apples 变量号放入 0-3 之间,一切正常,它会将其写入表中。但如果我在这里放 4 f.e.什么都没发生。
你能帮我解决这些问题吗?
谢谢。
【问题讨论】:
-
创建一个 while 循环,在该循环中循环直到苹果数为 0。填充一个数组,直到用完苹果,从每个碗的苹果数中减去 3,直到苹果数为 0。while( $apples > 0 ) if $apples > 3 make bowl $apple - 3 if( $apples
-
@user2992063 试试我的答案,我相信你会得到你的解决方案
标签: php mysql conditional-statements