具体来说,我想要一个基于用户输入的乘法表.我只需要一张表,因为输出已经正确了.
假设我的输入乘数是2.
这是我尝试做表时的代码.
<!DOCTYPE html>
<html>
<head>
<title> Multiplication Table </title>
</head>
<body>
<form method="POST" action="#">
Enter Multiplier: <input type="text" name="mult"> <br>
<input type="submit" name="m" value="Multiply">
</form>
<table border="1">
<?PHP
if(isset($_POST["m"])){
$mult = 0;
$x = 1;
$mulpli = 1;
$pro = 0;
$mult=$_POST["mult"];
while($mulpli <= $mult)
{
echo "<tr>". "<th>". " ";
echo "<th>". $mulpli;
while($x <= $mult)
{
$pro=$x*$mulpli;
echo "<tr>";
echo "<th>". $x;
echo "<th>". $pro;
$x=$x+1;
}
$x = $x-$mult;
$mulpli=$mulpli+1;
}
}
?>
</th></th></tr></th></th></tr>
</table>
</body>
</html>
表:
我想要的输出:
解决方法:
这应该做.我使用PHP的alternative syntax来获得更清晰的查看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multiplication Table</title>
<style type="text/css">
table, th, td { border: 1px solid black; }
th, td { text-align: center; }
</style>
</head>
<body>
<form method="post">
<label>Enter multiplier limit: <input type="text" name="limit"></label>
<button type="submit">Show Table</button>
</form>
<?PHP if (isset($_POST['limit'])):
$limit = max(1, (int)$_POST['limit']);
?>
<table>
<tr>
<?PHP for ($x = 0; $x <= $limit; $x++): ?>
<th scope="col"><?= $x ?: '' ?></th>
<?PHP endfor ?>
</tr>
<?PHP for ($y = 1; $y <= $limit; $y++): ?>
<tr>
<th scope="row"><?= $y ?></th>
<?PHP for ($x = 1; $x <= $limit; $x++): ?>
<td><?= $y * $x ?></td>
<?PHP endfor ?>
</tr>
<?PHP endfor ?>
</table>
<?PHP endif ?>
</body>
</html>