PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
CREATE TABLE users (`user_name` varchar(25), `age` smallint, `previous_level` varchar(20), `current_level` varchar(20)) ; INSERT INTO users (user_name, age, previous_level, current_level) VALUES ('User1', 25, 'N/A', 'blue'), ('User2', 30, 'blue', 'bronze'), ('User3', 28, 'bronze', 'silver'), ('User4', 35, 'silver', 'gold'), ('User5', 22, 'gold', 'diamond'), ('User6', 27, 'N/A', 'blue'), ('User7', 33, 'blue', 'bronze'), ('User8', 29, 'bronze', 'silver'), ('User9', 26, 'silver', 'gold'), ('User10', 31, 'gold', 'diamond'), ('User11', 24, 'N/A', 'blue'), ('User12', 32, 'blue', 'bronze'), ('User13', 34, 'bronze', 'silver'), ('User14', 23, 'silver', 'gold'), ('User15', 36, 'gold', 'diamond'), ('User16', 29, 'N/A', 'blue'), ('User17', 27, 'blue', 'bronze'), ('User18', 30, 'bronze', 'silver'), ('User19', 26, 'silver', 'gold'), ('User20', 25, 'gold', 'diamond'); Select * from users;
Copy Clear
Copy Format Clear
<?php $user_name = 'Floris'; $user_pass = 'abcd'; $previousLevels = [ 'bronze' => ['blue'], 'silver' => ['blue', 'bronze'], 'gold' => ['blue', 'bronze', 'silver'], 'diamond' => ['blue', 'bronze', 'silver', 'gold'], ]; $curLevel = 'gold'; // $previousLevelString = $previousLevels[$curLevel]; // Split the previous levels string into an array // $previousLevelsArray = explode(', ', $previousLevelString); $previousLevelsArray = $previousLevels[$curLevel]; // Database connection using PDO try { // Set PDO to throw exceptions on error $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("Connection failed: " . $e->getMessage()); } // Generate named placeholders for the IN clause $placeholders = array_map(function($index) { return ":prev_level_$index"; }, array_keys($previousLevelsArray)); // Prepare the SQL query with the dynamically generated named placeholders $query = "SELECT * FROM users WHERE current_level = :cur_level AND previous_level IN (".implode(', ', $placeholders).")"; // Prepare the query $stmt = $pdo->prepare($query); // Bind parameters $stmt->bindValue(':cur_level', $curLevel); foreach ($previousLevelsArray as $key => &$value) { $stmt->bindValue(":prev_level_$key", $value); } // Execute the query $stmt->execute(); // Fetch the result set $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // Output each row foreach ($result as $row) { print_r($row); }
Show:  
Copy Clear