0

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?

1 Answer 1

0

It looks like you need to move the prepare statement into the if section, adding a second prepare statement for the second case. It'd probably be better (for readability's sake) if you also added an else for when id === 'all'.

2
  • Thanks. That's the way I currently have it but man, it just looks like there has to be a better way of handling this. You might be right though.
    – NaN
    Sep 30, 2012 at 15:13
  • I guess you were right. :) I've credited you for the answer. Thank you.
    – NaN
    Sep 30, 2012 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.