Reputation: 27
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.
Upvotes: 1
Views: 866
Reputation: 12189
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]);
Upvotes: 1
Reputation: 263933
You have to use ==
or ===
in your if
condition
if ($op == 'LESS THAN')
{
// code here
}
elseif ($op == 'GREATER THAN')
{
// code here
}
// .......
Upvotes: 1