在各
<option>部分中,只需修改一下即可。添加
selected条件:
<div > <div > <div > <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "db"; // Create connection $con = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT fruits FROM fruits"; $result = $con->query($sql); ?> <label for="fruits">Treatment Type: </label> <select name="fruits" id="fruits" > <option value="" <?php if(!isset($_POST['fruits']) || (isset($_POST['fruits']) && empty($_POST['fruits']))) { ?>selected<?php } ?>>--Select--</option> <?php while($row = $result->fetch_assoc()) { ?> <option value="<?php echo $row['fruits']; ?>" <?php if(isset($_POST['fruits']) && $_POST['fruits'] == $row['fruits']) { ?>selected<?php } ?>><?php echo $row['fruits']; ?></option> <?php } ?> </select> </div> </div></div>结果页:
<?php $con = mysqli_connect("","","","");// Check connection if(mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); $fruits = mysqli_real_escape_string($con, $_POST['fruits']); if(!empty($fruits)) { $sql1 = "SELECT * FROM treatment WHERe fruits LIKE '%$fruits%'"; $result = mysqli_query($con, $sql1); $count = mysqli_num_rows($result); } else $count = 0; ?> <table > <thead> <tr> <th>Name</th> <th>Type</th> <th>Fruits</th> </tr> </thead> <?php if ($count > 0) { while($row = mysqli_fetch_assoc($result)) { ?> <tbody data-link='row' > <tr> <td><a href='#'><?php echo $row['name']; ?></a></td> <td><?php echo $row['type']; ?></td> <td><?php echo $row['fruits']; ?></td> </tr> </tbody> <?php } } else echo "0 results"; ?> </table> <?php mysqli_close($con); ?>


