我有一个HTML表单,该表单使用PHP while循环从MYSQLi数据库填充选择菜单。下面的代码;
$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1 ";
$result = mysqli_query($conn, $query);
echo '<p><label for="current_clients">Select Client by name: </label>
<select id="current_clients" name="current_clients">
<option> -- Select Client -- </option>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<option>'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
}
echo '</select>';
上面的作品,表格中填入了所需的客户记录。但是,我随后希望使用此数据链接到单个客户端页面,我尝试使用它
echo ' <a href="selected_client.php?id='.$row['id'].'" onClick="this.form.submit()">Go!</a>';
这不起作用,所以我尝试将表单操作设置为
action="selected_client.php?id='.$row['id'].'"
方法为“ GET”,这也不起作用。正如您在查询中看到的那样,我也在表中选择“ id”,以便稍后可以调用数组的该部分,我只是特别不需要或不想回显它。使用表单操作方法,未设置$ row ['id']变量,使用onClick方法,出现“尝试访问类型为null的值的数组偏移量”错误。
我以为在执行表单操作之前需要先设置变量,但是我不认为在不移动while循环或至少不从其返回值的情况下如何做到这一点。是否可以在提交时而不是在表单顶部调用表单方法和操作?这有什么区别吗?
编辑;根据要求,我尝试对表单使用隐藏方法
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" value="'.$row['id'].'">';
仍返回错误类型为null的值。
编辑#2-所有内联代码。
$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1 ";
$result = mysqli_query($conn, $query);
echo '<form action="selected_client.php" method="get">
<fieldset>';
echo '<p><label for="current_clients">Select Client by name: </label>
<select id="current_clients" name="current_clients">
<option> -- Select Client -- </option>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<option>'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
}
echo '</select>';
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" value="'.$row['id'].'">';
echo '</fieldset></form>';
[添加onChange事件并将选定的值传递给某个函数,在该函数中,使用此选定的值设置隐藏字段。现在您可以提交表单,并且可以接收选定的值。下面是解决方案。
$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1";
$result = mysqli_query($conn, $query);
echo '<form action="selected_client.php" method="get">
<fieldset>';
echo '<p><label for="current_clients">Select Client by name: </label>
<select id="current_clients" name="current_clients" onChange="setId(this.value);">
<option value=""> -- Select Client -- </option>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<option value="'.$row['id'].'">'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
}
echo '</select>';
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" id="hidden_field" value="">';
echo '</fieldset></form>';
添加此脚本以在隐藏字段中设置值。
<script>
function setId(rowValue){
document.getElementById("hidden_field").value=rowValue;
}
</script>