PHP 8.1 - guide with PDO Prepared Statements Not Binding Correctly with Default NULL Values
I'm converting an old project and I've been struggling with this for a few days now and could really use some help. I'm experiencing an scenario with PDO prepared statements in PHP 8.1 where default NULL values for parameters aren't being bound correctly. I'm trying to execute a query that optionally filters results based on user input, but if a filter is not provided, it should default to NULL. Hereβs a simplified version of my code: ```php $pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $query = 'SELECT * FROM users WHERE (:filter IS NULL OR username = :filter)'; $stmt = $pdo->prepare($query); $filter = isset($_GET['username']) ? $_GET['username'] : null; $stmt->bindValue(':filter', $filter, $filter === null ? PDO::PARAM_NULL : PDO::PARAM_STR); $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); ``` When I call this code without providing the `username` parameter in the URL, I expect to receive all users, but it seems to return an empty array instead. I double-checked that the users table contains data, so that shouldn't be the scenario. The SQL query generated appears to be correct, yet it behaves unexpectedly. I've tried hardcoding the filter to `NULL` directly and it works as expected. My question is: why does the conditional binding of parameters unexpected result in this case? Is there a better way to handle optional parameters in PDO when dealing with NULL values? I'm developing on Debian with Php. Is this even possible?