mySQL returns all rows when field=0

断了今生、忘了曾经 提交于 2019-11-26 11:18:33

问题


I was making some tests, and it was a surprise when i was querying a table, and the query SELECT * FROM table WHERE email=0 returned all rows from the table.

This table has no \'0\' values and it\'s populated with regular e-mails.

Why this happens? This can lead to serious security problems.

Is there a way to avoid this without modifying the query?

Am i missing something here?

Thanks.


回答1:


This is because it is converting the email field (which I assume is a varchar field) to an integer. Any field without a valid integer will equate to 0. You should make sure that you only compare string fields to string values (same goes for dates, comparing to dates). The query should be as follows.

SELECT * FROM table WHERE email='0';



回答2:


Your email column is a CHAR or VARCHAR type. When you use the condition email = 0, MySQL is casting the contents of the email column to an integer in order to compare them with the 0 you supplied. Had you surrounded your 0 in quotes, the query would work as expected. (email = '0')

Converting a non-numeric string to an integer in MySQL will result in 0.

mysql> SELECT CAST('email@example.com' AS SIGNED);
+-------------------------------------+
| CAST('email@example.com' AS SIGNED) |
+-------------------------------------+
|                                   0 |
+-------------------------------------+

In contrast, if you attempted the same thing with numeric strings, they may cast correctly:

mysql> SELECT CAST('12345' AS SIGNED);
+-------------------------+
| CAST('12345' AS SIGNED) |
+-------------------------+
|                   12345 |
+-------------------------+



回答3:


The email field is probably characters and you are matching numeric values.

Try with,

SELECT * FROM table WHERE email='0';



回答4:


if you want to get all record in which email column should not be blank or empty, then you can use

SELECT * FROM table WHERE email IS NOT NULL;


来源:https://stackoverflow.com/questions/7880936/mysql-returns-all-rows-when-field-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!