如何使用php在textarea字段中显示多个值?
我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Generate Random Numbers</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<?php
if(isset($_POST['submit']) && !empty($_POST['start']) && !empty($_POST['end']) && !empty($_POST['how_many'])){
$start = $_POST["start"];
$end = $_POST["end"];
$how_many = $_POST["how_many"];
/* function hw(){
$how_many = $_POST["how_many"];
$start = $_POST["start"];
$end = $_POST["end"];*/
for ($x=1; $x<=$how_many; $x++){
$output= rand($start,$end);
}
}
//The rand() function generates a random integer.
//Tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100).
else{
$start="";
$end="";
$how_many="";
$output="";
}
?>
Range start: <input type = "text" name = "start" value = "<?php echo $start; ?>"><br>
Range end: <input type = "text" name = "end" value = "<?php echo $end; ?>"><br>
How many? <input type = "text" name = "how_many" value = "<?php echo $how_many; ?>"><br>
Output: <textarea><?php echo $output;?></textarea>
<input type = "submit" name = "submit" value ="Generate Random Numbers">
</form>
</body>
</html>
如下图所示,文本区域中只显示1个输出,尽管它处于循环中。
答案 0 :(得分:0)
您需要在for
循环内部使用连接(在最初将$output
声明为空字符串之后)。
我建议对用户输入设置一些限制,所以事情并不荒谬。您可以将它们设置为您想要的任何内容。
我将所有POST数据验证和变量声明打包到if
语句中。
我将输入的type
值更改为数字,并对这些字段实施了限制。
我个人不喜欢跳进和跳出php,所以我留在php内部并写回声,直到我完成使用变量。如果你愿意,欢迎你们反弹。
未经测试的代码:
<!DOCTYPE html>
<html>
<head>
<title>Generate Random Numbers</title>
</head>
<body>
<?php
// subjective developer configurations
$random_min=0; // developer must set this limit
$random_max=100; // developer must set this limit
$iterations_min=1; // developer must set this limit
$iterations_max=20; // developer must set this limit
echo "<form method=\"POST\" action=\"",htmlspecialchars($_SERVER['PHP_SELF']),"\">";
if(isset($_POST['submit'],$_POST['start'],$_POST['end'],$_POST['how_many'])
&& ($start=$_POST['start'])>=$random_min && $_POST['start']<=$random_max
&& ($end=$_POST['end'])>=$random_min && $_POST['end']<=$random_max
&& ($how_many=$_POST['how_many'])>=$iterations_min && $_POST['how_many']<=$iterations_max){
$output='';
for($x=0; $x<$how_many; ++$x){
$output.=rand($start,$end)."\n";
}
}else{
$start=$end=$how_many=$output='';
}
echo "Range start: <input type=\"number\" name=\"start\" min=\"$random_min\" max=\"$random_max\" value=\"$start\"><br>";
echo "Range end: <input type=\"number\" name=\"end\" min=\"$random_min\" max=\"$random_max\" value=\"$end\"><br>";
echo "How many? <input type=\"number\" name=\"how_many\" min=\"$iterations_min\" max=\"$iterations_max\" value=\"$how_many\"><br>";
echo "Output: <textarea>$output</textarea><br>"; // you may want to add a conditional rows attribute here to improve display
?>
<input type="submit" name="submit" value="Generate Random Numbers">
</form>
</body>
</html>