Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL returns all rows with empty string as where clause

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(""));
like image 779
Anson Kao Avatar asked Oct 04 '11 15:10

Anson Kao


People also ask

Is empty string considered NULL in MySQL?

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.

How do I check if a row is empty in MySQL?

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.

How do I check if a field is empty in MySQL?

The IS NULL operator is used to test for empty values (NULL values).


1 Answers

Try using following, if you are using codeigniter:

$this->db->where("field_name = ''");
like image 167
Ghazanfar Mir Avatar answered Oct 21 '22 06:10

Ghazanfar Mir