0

I have a query, and in the where statement I want to insert a ternary operator like this:

WHERE 

 $self->is_defined? 'some_column = $self->defined' : 'some_other_column = $self->defined_some'
 AND blah blah blah
 AND blah blah blah

Something like that. How to do it?

As of now my code is this which doesnt work:

"SELECT blah blah blah

    WHERE 
     "$self->is_defined ? 'o.project_id = "$self->project_id"' : 'o.brand_id = "$self->brand_id"'"

1 Answer 1

0

First, method calls doesn't interpolate inside double quotes, and even less so inside single quotes.

You should use placeholders when creating sql in order to avoid sql injection,

my $sql = "SELECT * from ... WHERE ";

my ($cond, $val) = $self->is_defined 
  ? ("some_column = ?", $self->defined)
  : ("some_other_column = ?", $self->defined_some);

# constructing final sql..
$sql .= $cond;

my $st = $db_handle->prepare($sql) or die $db_handle->errstr;
$st->execute($val) or die $st->errstr;
4
  • My code contains comma too, I removed it because I dont know what it does, Can you explain to me what the comma is used for there and the question mark too after the equal sign? Thanks Oct 25, 2013 at 6:32
  • Ahhh. I know what the question mark does, it serves as a container to be replaced on the right part of the comma. Thanks Oct 25, 2013 at 6:33
  • HEy, where is the sql statement there? i need it to insert to an sql statement Oct 25, 2013 at 6:38
  • @user2881063: "servers as a container to be replaced on the right part of the comma" not quite; the commas are just there because you are assigning two values to two variables - a list assignment. the questionmark in the sql passed to prepare is a container to be replaced by what is passed to execute later on.
    – ysth
    Oct 25, 2013 at 6:51

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.