从数据库中选择菜单时,PHP MySQL从下拉菜单中选择选项

时间:2018-06-12 07:12:43

标签: php mysqli

我的网页出现问题。我试图通过很多教程解决它,但我不知道如何使它工作。简单地说,我有一个对象数据库。当我选择对象时,页面将重定向到另一个显示有关该对象的所有信息的位置。但我需要在下拉菜单中保留所选的选项。有110个对象,所以如果我选择对象编号25,信息会显示,但下拉菜单不会保留在25号。有人可以帮我吗?

<form action="dbobj2.php" method="post" name="form1">
    Zoznam objektov<br>
    <?php
        include('System/connect.php');
        $sql = "SELECT Objekt FROM DBObj";
        $result = mysqli_query($db,$sql);
        echo "<select name='Objekt'>";
        while ($row = mysqli_fetch_array($result)) {
            echo "<option value='" . $row['Objekt'] . "'>" . $row['Objekt'] . "</option>";
        }
        echo "</select>";
    ?>
    <input name="btnSubmit" type="submit" value="Vyber">
</form>
<?php
    echo $_POST['Objekt'];
    echo "<hr>";
        $strSQL = "SELECT * FROM DBObj WHERE Objekt = '".$_POST['Objekt']."' ";
        $objQuery = mysqli_query($db,$strSQL);
        $objResult = mysqli_fetch_array($objQuery);
        $imgRes=$objResult['URLobr'];
    echo '<img src="http://page.sk.sk/imgs/'.$imgRes.'" alt="obj" height="600" width="800"/>';
    echo "<hr>";
    echo $objResult['Text'];
?>

第一页php

<form action="dbobj2.php" method="post" name="form1"> 
  Zoznam objektov<br>
Vyberte si zvolený objekt z menu a stlačte tlačidlo výber<br>
<?php
include('System/connect.php');
$sql = "SELECT Objekt FROM DBObj";
$result = mysqli_query($db,$sql);
echo "<select name='Objekt'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Objekt'] . "'>" . $row['Objekt'] . "</option>";
}
echo "</select>";
?>

3 个答案:

答案 0 :(得分:0)

您可以通过变量发送该值$_POST['Objket'],让我们说$selected_value,然后在选项标签中发送

<option value='" .$row['Objekt']. "' '.if($row['Objket']==$selected_value) echo selected.'>" .$row['Objekt']. "</option>

答案 1 :(得分:0)

检查post值是否与循环中的对象id匹配。

$selcted = $_POST['Objekt'] == $row['Objekt'] ? ' selected' : '';

如果$selected设置为“已选中”并添加到选项中。

echo "<option value='" . $row['Objekt'] . "'" . $selected . ">" . $row['Objekt'] . "</option>";

答案 2 :(得分:0)

当您选择一个选项并单击按钮时,它将起作用,否则为否。

if(isSet($_POST['Objekt']))
{
echo $_POST['Objekt'];
    echo "<hr>";
        $strSQL = "SELECT * FROM DBObj WHERE Objekt = '".$_POST['Objekt']."' ";
        $objQuery = mysqli_query($db,$strSQL);
        $objResult = mysqli_fetch_array($objQuery);
        $imgRes=$objResult['URLobr'];
    echo '<img src="http://page.sk.sk/imgs/'.$imgRes.'" alt="obj" height="600" width="800"/>';
    echo "<hr>";
    echo $objResult['Text'];
}