I want to conditionally build a SQL statement and am having issues. In this case, there may be a WHERE clause or not.
$sql=null;
$arr='';
if( $id != 'all' ){
$sql = ' WHERE type = :type AND id=:id';
$arr = array(':type'=>$type,':id'=>$id);
}
$stmt = $dbh->prepare("SELECT * FROM table $sql");
$stmt->execute($arr);
...
If the id is equal to ‘all’, then I just want to rewrite the sql without a WHERE clause.
Since I have to pass $arr to execute, I get the folowing error when id = ‘all’ because execute is expecting a value:
PHP Warning: PDOStatement::execute() expects parameter 1 to be array, string given
I’ve tried passing execute an empty array but get an error as well.
How do I do this without having to rewrite two complete blocks of sql, each with its own execute statememt?
It looks like you need to move the
preparestatement into theifsection, adding a second prepare statement for the second case. It’d probably be better (for readability’s sake) if you also added anelsefor whenid === 'all'.