tags:

views:

58

answers:

3

by default i have one column in mysql table to be NULL.

i want to select some rows but only if the field value in that column is not NULL.

what is the correct way of typing it?

    $query = "SELECT *
            FROM names
            WHERE id = '$id'
            AND name != NULL";

is this correct?

+7  A: 
 AND name IS NOT NULL

(NULL comparisons require the special IS and IS NOT operator in SQL)

Larry Lustig
capitalised field name will error
Andy
Beg pardon, working in a couple of case-insignificant DBMSes this week. Will edit.
Larry Lustig
@Andy: MySQL is case-insensitive for columns'/tables' names.
Crozin
@Crozin: http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html : "Consequently, the case sensitivity of the underlying operating system plays a part in the case sensitivity of database and table names."
VolkerK
@Crozin it's actually case-insensitive for column names, but *table names* are case sensitive. Apologies.
Andy
+3  A: 

You should use (assuming $id is an integer):

   $query = "SELECT *
            FROM names
            WHERE id = '" . (int) $id ."'
            AND name IS NOT NULL";

You must use IS NULL or IS NOT NULL when working with NULL values

Andy
Keep in mind that the php integer and the MySQL field type may have different value ranges. So `(int)$id` may be feasible, may be not.
VolkerK
@VolkerK I tremble at the sight of unescaped variables going into SQL-bound strings, just raising awareness :)
Andy
@Andy is it required to assume $id as integer? i never did such thing, but never meet the problem!!!
Syom
A: 

@Andy: my bad. I've only tested for columns' names.

Crozin