[英]Only getting the last row from a table using POST with PHP
我是PHP的新手,我在从POST获取数据时遇到问题。 我有一个SQL查询,该查询从表3列中选择,我以表的形式回显。 请注意,只有第三列应该是输入类型。 尽管表显示正常(所有值均来自mySQL),但是当我从$_POST
打印第3列变量时,仅显示最后一个值。 这是代码:
$result = mysql_query("SELECT `id`, `component`,`percentage` FROM `waste_percentage` ")or die(mysql_error());
$row = mysql_fetch_array($result);
echo "<table border='1' cellspacing='0'>
<tr>
<th>α/α</th>
<th>Ρεύμα</th>
<th>Ποσοστό</th>
</tr>";
while($row = mysql_fetch_array($result))
{
$num = mysql_numrows($result);
$i=0;
while ($i < $num)
{
$field1 = $i +1;
$field2=mysql_result($result,$i,"component");
$field3=mysql_result($result,$i,"percentage");
$i++;
echo "<form action=\"\" method=\"post\">";
echo "<tr>";
echo "<td> $field1 </td>";
echo "<td> $field2 </td>";
echo "<td>" . "<input type=\"text\" name=\"percentage\" value=" . $field3 . " </td>";
echo "<td>" . "<input type=\"hidden\" name=\"hidden\" value=" . $row['id'] . " </td>";
echo "</tr>";
}
}
echo "</table>";
echo "<input name=\"Submitpercent\" type=\"submit\" value=\"Συνέχεια\" />";
echo "</form>";
//When I try to output
if(isset($_POST['Submitpercent']))
{
$user_percentage [] = $_POST['percentage'];
print_r ($user_percentage);
}
输出为:“数组([0] => 13.60)”。 我将不胜感激任何帮助! 提前致谢。
您忘记正确结束<input>
标记,如下所示:
echo "<td>" . "<input type=\"text\" name=\"percentage\" value=\"" . $field3 . "\"> </td>";
echo "<td>" . "<input type=\"hidden\" name=\"hidden\" value=\"" . $row['id'] . "\"> </td>";
您的代码有多个缺陷。 如前所述,您忘记了关闭标签。
您也可以在内部打开<form>
,但是只关闭一次(在提交按钮之后)。
另一个问题是您有多个具有相同名称的字段: percentage
,这可以通过将name="percentage"
替换name="percentage"
name="percentage[]"
。 如果您使用PHP访问它,则将有一个包含百分比的数组,而不仅仅是一个字段
首先,您在这里跳过第一行:
$row = mysql_fetch_array($result);
// ...
while($row = mysql_fetch_array($result))
删除查询正下方的$row = ...
其次,您要遍历行,而要遍历行,这很奇怪。 将while
循环更改为(并关闭<inputs>
):
$i=0;
while($row = mysql_fetch_array($result))
{
$field1 = ++$i;
$field2 = $row['component'];
$field3 = $row['percentage'];
echo "<tr>";
echo "<td> $field1 </td>";
echo "<td> $field2 </td>";
echo "<td>" . "<input type=\"text\" name=\"percentage\" value=\"" . $field3 . "\"> </td>";
echo "<td>" . "<input type=\"hidden\" name=\"hidden\" value=\"" . $row['id'] . "\"> </td>";
echo "</tr>";
}
}
最后,在打开<table>
之前先打开<form>
<table>
。
您需要为表单输入使用特殊的“数组”表示法,以便同一字段可以多次包含在页面上;
更改percentage
,以percentage[]
; 您也缺少代码中输入标签的结束标签
echo '<td><input type="text" name="percentage[]" value="' . $field3 . '" /></td>";
然后,显示值;
if (!empty($_POST['percentage'])) {
print_r($POST['percentage']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.