I discovered this problem while debugging CodeIgniter active record as shown below:
$this->db->from("table_name");
$this->db->where("field_name", "");
$result = $this->db->get()->result_array();
The resulting query is:
SELECT * FROM `table_name` WHERE `field_name` = 0; // Returns all rows in table
Even though the empty string is cast to 0, we expect an empty result since table_name
.field_name
is full of non-empty string values. However, I get the entire table from this query. Anyone understand why? This is not intuitive at all.
I tried the query without the cast to 0 and it works:
SELECT * FROM `table_name` WHERE `field_name` = ""; // Empty result
Why the cast to 0?
EDIT: The same cast to 0 happens with this alternative CodeIgniter syntax:
$this->db->query('SELECT * FROM table_name WHERE field_name = ?', array(""));
In PHP, the empty string equals to a NULL value, but in MySQL, the case is the different i.e. empty string is not equal to NULL value.
SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.
The IS NULL operator is used to test for empty values (NULL values).
Try using following, if you are using codeigniter
:
$this->db->where("field_name = ''");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With