I want to be able to pass something into an SQL query to determine if I want to select only the ones where a certain column is null. If I was just building a query string instead of using bound variables, I’d do something like:
if ($search_undeleted_only) { $sqlString .= ' AND deleted_on IS NULL'; }
but I want to use bound queries. Would this be the best way?
my $stmt = $dbh->prepare(... 'AND (? = 0 OR deleted_on IS NULL) '); $stmt->execute($search_undeleted_only);
Yes; a related trick is if you have X potential filters, some of them optional, is to have the template say
' AND ( ?=-1 OR some_field = ? ) ', and create a special function that wraps the execute call and binds all the second ?s. (in this case, -1 is a special value meaning ‘ignore this filter’).Update from Paul Tomblin: I edited the answer to include a suggestion from the comments.