我是编程新手,需要php中的循环帮助。我需要创建页面,以便当您输入两个不同的数字时,它们之间的所有数字都显示在页面上,表格中,如果结束数字低于起始数字,则会出现错误。任何帮助表示赞赏。
<body>
<form method="post">
Starting Number: <br>
<input type="text" name="start" required><br><br>
Ending Number: <br>
<input type="text" name="end" required><br><br>
<input type="submit" name="subBtn"<br><br><br>
</form>
<?php
// using if statements to automatically set the grade and comment
if ($_POST['subBtn'])
// store the posted values from the form in variables
$start = $_POST['start'];
$end = $_POST['end'];
?>
<table border="1" style="width:100%" padding="15px">
<tr>
<td>Temperature (Celcius)</td>
<td>Temperature (Kelvin)</td>
<td>Temperature (Farenheit)</td>
</tr>
<tr>
<td>
<?php
$c = $start;
while($start >= $end){?>
<?php echo $start--;?>
<?php }?>
</td>
<td><?php
$k = start + 273;
while($k != $end + 272){?>
<?php echo $k--;?>
<?php }?>
</td>
<td>
<?php
$f = 212;
while($f >= 31){?>
<?php echo $f-=1.8;?>
<?php }?>
</td>
</tr>
</table>
</body>
答案 0 :(得分:1)
首先,使用开始和结束括号:
if ($_POST['subBtn']) {
$start = $_POST['start'];
$end = $_POST['end'];
...并在TABLE的末尾关闭它:
</table>
<?php } ?>
然后,进行测试:
if ($start <= $end){
echo 'Start temp needs to be higher than End temp';
}else{
... your other code here
最后,您的开尔文计算存在无限循环。检查你的计算并更新循环。
答案 1 :(得分:0)
首先要检查错误,我会做这样的事情:
if($end < $start) {
echo 'Oops, your end number is lower than your start';
}
然后对于实际的显示逻辑,这应该做你需要的:
for($i = $start; $i < $end; $i++) {
echo '<td>'.$i.'</td>';
}
这会显示$start
和$end
之间的数字,如果你想要包含它,那么在for循环的逻辑部分使用&lt; =。
我不是100%肯定,但我相信您需要在<form>
元素中指定操作,我相信它默认为当前页面,因此您应该能够将其用于测试。
我建议也许将PHP逻辑移到HTML之上只是为了将它拆分出来,然后你可以将实际项目放入变量并在html中回显。