我有以下代码来生成我的选项:
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $rows) {
$id = $rows[MyID];
$option.="<option>".$id."</option>";
}
?>
<select name="options" id="options" class="options">
<option value="$id">Select an Option</option>
<?php echo $option?>
</select>
我想在下一个查询中使用所选选项的值..像这样:
<?php
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
由于某种原因,这不起作用。你能帮忙吗?感谢
答案 0 :(得分:0)
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="post" action"(`The url of the next page`)">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
下一页:
<?php
if(isset($_POST['submit']) && isset($_POST['options'])) {
$option = $_POST['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
}
fetchAll()
,您应该将其分配给变量,然后循环执行该变量。$row[MyID]
MyID应包含在''或“”中,因为索引是一个字符串,因此$row['MyId']
if(isset())
作为REQUEST变量($ _GET,$ _POST),这样可以防止PHP在没有它们的情况下加载页面时抛出错误。如果您有任何其他问题,我很乐意提供帮助。
希望这有帮助! :)
修改强>
<?php
if(isset($_GET['submit']) && isset($_GET['options'])) {
$option = $_GET['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
/**
* You'll need to put the logic for the query above here
**/
} else {
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="get" action"">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
<?php
} // End of else
?>
我还更改了表单方法以获取和删除操作,因此它将提交到当前页面。