如何实现PHP下拉选框排除已存入数据库的已选选项?
Alright, let's tackle this problem. The goal is to hide any options that have already been selected and stored in the database when the page reloads. Here's how to modify your code to make that happen:
Step 1: Fetch already selected codes from the database
First, you need to pull all the codes that have been saved to your database so you know which ones to exclude. I'll use PDO for this example (since it's secure and widely used), but you can adjust it to use mysqli if that's what you're working with.
// Replace these with your actual database credentials $dbHost = 'localhost'; $dbName = 'your_database_name'; $dbUser = 'your_username'; $dbPass = 'your_password'; // Connect to the database try { $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("Database connection failed: " . $e->getMessage()); } // Fetch all selected codes into an array $stmt = $pdo->query("SELECT code FROM your_table_name"); // Replace 'your_table_name' with your actual table $selectedCodes = $stmt->fetchAll(PDO::FETCH_COLUMN);
Note: If this is user-specific (e.g., each user has their own selected codes), add a WHERE clause to the query, like:
$userId = $_SESSION['user_id']; // Assuming you're using sessions for user auth $stmt = $pdo->prepare("SELECT code FROM your_table_name WHERE user_id = ?"); $stmt->execute([$userId]); $selectedCodes = $stmt->fetchAll(PDO::FETCH_COLUMN);
Step 2: Modify the dropdown to skip selected codes
Now, update your loop to only render options that aren't in the $selectedCodes array. We'll use in_array() to check if the current code has already been saved.
<select class="form-control text-center" name="code" id="Code" > <option value="">Select Code</option> <?php for($i = 1; $i <= 20; $i++){ // Only show the option if it hasn't been selected before if (!in_array($i, $selectedCodes)) { ?> <option value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php } } ?> </select>
If you're using mysqli instead of PDO
Here's the equivalent code for fetching selected codes with mysqli:
$conn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $result = mysqli_query($conn, "SELECT code FROM your_table_name"); $selectedCodes = []; while ($row = mysqli_fetch_assoc($result)) { $selectedCodes[] = $row['code']; } mysqli_close($conn);
Quick reminder
Make sure your form submission code correctly inserts the selected code into the database when the user submits the form. That part should already be in place, but double-check that you're inserting the value from $_POST['code'] into the correct field.
内容的提问来源于stack exchange,提问作者Usama Hadi

