1

I need your help.

I have a PHP code that I use to query a MySQL database after selecting a certain operator. The operators that I have from the dropdown list are "LESS THAN, GREATER THAN, and EQUALS". The problem I have is; whichever operator I select, the result that I get from the database is always for the "LESS THAN" operator. That is, it give me the same result whether I select "LESS THAN", "GREATER THAN" or "EQUALS". I tried to locate the problem but failed. Here is the code that I use:

            if ($op='LESS THAN') {
        $query = "SELECT * FROM tbl_reservoir WHERE res_vol < '$vol'";
    } elseif ($op='GREATER THAN') {
            $query = "SELECT * FROM tbl_reservoir WHERE res_vol > '$vol'";
    } elseif ($op='EQUAL') {
         $query = "SELECT * FROM tbl_reservoir WHERE res_vol = '$vol'";
    } 

$op is a variable that holds the operator, and "res_vol" is a field that I compare with from the database table.

2
  • In addition to the answers - if you have just three options, you don't need a final if ($op == 'EQUAL') line. You know if you reach that, then neither of the previous two options was chosen. I tend to make that option an else - I think it makes the code a little more readable. Commented Sep 17, 2012 at 0:56
  • The way you're building your queries leaves you open to a SQL injection attack. Please take a look at bobby-tables.com/php.html to find out about how to use parametrized queries. Commented Sep 17, 2012 at 2:07

2 Answers 2

1

You have to use == or === in your if condition

if ($op == 'LESS THAN')
{
  // code here
}
elseif ($op == 'GREATER THAN')
{
  // code here
}
// .......
Sign up to request clarification or add additional context in comments.

2 Comments

Hahahaa...., Finding a small problem can sometimes be difficult. Thank you very much John Woo. I felt like a fool after seeing your response. Is not like I don't know anything about the operator. I don't know what was happening to me. Thank you once again
@Kriz don't call yourself a fool, human as we are, we do always made mistakes :)
1

You're using an assignment operator (=) where you want the equality operator (==), so your code should read:

        if ($op=='LESS THAN') {
    $query = "SELECT * FROM tbl_reservoir WHERE res_vol < '$vol'";
} elseif ($op=='GREATER THAN') {
        $query = "SELECT * FROM tbl_reservoir WHERE res_vol > '$vol'";
} elseif ($op=='EQUAL') {
     $query = "SELECT * FROM tbl_reservoir WHERE res_vol = '$vol'";
} 

but, you could simplify this to:

static $map = array('LESS THAN' => '<', 'GREATER THAN' => '>', 'EQUAL' => '=');
if (!isset($map[$op])) {
    throw new Exception(sprintf("Unexpected operator '%s', $op));
}
$query = sprintf("SELECT * FROM tbl_reservoir WHERE res_vol %s '$vol'", $map[$op]);

1 Comment

I have really been a fool Ross. Thank you very much

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.