我是编程新手,需要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>
首先,使用左括号和右括号:
if ($_POST['subBtn']) {
$start = $_POST['start'];
$end = $_POST['end'];
并在表格末尾关闭:
</table>
<?php } ?>
然后,执行测试:
if ($start <= $end){
echo 'Start temp needs to be higher than End temp';
}else{
... your other code here
最后,你的开尔文计算有一个无限循环。检查你的计算并更新循环。
首先要检查错误,我会做这样的事情:
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循环的逻辑部分。
我不能100%确定,但我认为你也需要在<form>
元素中指定操作,我认为它默认为当前页面,所以你应该能够让它进行测试。
我建议将PHP逻辑移到HTML之上,只是为了将其拆分一点,然后可以将实际项目放入一个变量中,并在HTML中回显它。