NOT NULL and empty records
What happens when a user leaves a field blank? If you require a value in the field, you wrote a verification script requiring a value. But some fields are OK to leave empty. MySQL will do any of three things: - Insert the value
NULL. This is the default action. - If you declared the column
NOT NULL (when you created the column, or by modifying the column), MySQL will leave the record empty. - In an
ENUM datatype, if you declared the column NOT NULL, MySQL will insert the first value of the enumerated set. In other words, MySQL treats the ENUM datatype as if you declared the first value to be the DEFAULT value. To work around this weirdness, make the first value a pair of single quotes (''), which means " empty set".
The difference between NULL and an empty record is that the % wild card finds empty records, but doesn't find NULL records. I have yet to find a situation where the latter result is desirable. In my experience, all columns should be declared NOT NULL. Then the following SELECT query works:
if (!$CITY) {$CITY = "%";}
$selectresult = mysql_query ("SELECT * FROM dbname
WHERE FIRST_NAME = 'Bob'
AND LAST_NAME = 'Smith'
AND CITY LIKE '$CITY'
");
The first line says that if the user doesn't specify
a city, the % wild card is used for the search, to find any city, or empty CITY records. If every record contains a city, then the query returns all Bob Smiths in your database. If some CITY records are empty, the query also returns all Bob Smiths in your database. But if some CITY records contain NULL, your query won't return the Bob Smiths with a NULL value in the CITY column.
Can we solve that problem with:
if (!$CITY) {$CITY = "%";}
$selectresult = mysql_query ("SELECT * FROM dbname
WHERE FIRST_NAME = 'Bob'
AND LAST_NAME = 'Smith'
AND (CITY LIKE '$CITY' OR CITY IS NULL)
");
Note that to search for NULL you must
use IS. = or LIKE will not find NULL values. If the user enters "Altoona" for the city, the query returns every Bob Smith in Altoona, and every Bob Smith with NULL in the CITY field. That isn't what the user wanted. It'd better to declare every column to be NOT NULL and avoid this problem.
One last pitfall to watch out for. If you add (or modify) columns after some records are already in your database, you may get a mixture of NULL and empty records. This is certain to screw up your SELECTqueries.
Next: Checkboxes and other HTML form processing >>
More PHP Articles
More By Thomas Kehoe