Home arrow MySQL arrow Page 2 - Null and Empty Strings

Making Null Safe in PHP - MySQL

Anyone who has programmed for any length of time has encountered the concepts of null and empty strings. They are not the same, and confusing the two can cause some serious problems. This article deals with these concepts in the context of PHP and MySQL.

TABLE OF CONTENTS:
  1. Null and Empty Strings
  2. Making Null Safe in PHP
  3. Null and MySQL
  4. Handling Null in MySQL
By: Shikhar Kumar
Rating: starstarstarstarstar / 13
December 02, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

A safe way to to handle this problem would be to use a custom isNull function, like so:

function isNull($var) {

 

if(is_null($var)) {

return true ;

} else if((string)$var == "") { // $var == "" will return true if $var = 0 that's why we need to cast into string

return true ;

} else if(count($var) < 1) { // return true even if its an empty array

return true ;

} else {

return false ;

}

 

}



Now the functional code becomes:


If ( isNull($var) ) { // returns true when var has value and $var is not equal to zero

echo $var ; // or do some processing

}


If your code is all object-oriented, you can put the function in one of the general classes as shown below:


Class GenClass

{


// class vars

....


function isNull()

{

.......

}



} // end of class


The functional code in this case becomes:


If ( $genClass->isNull($var) ) { // returns true when var has value and $var is not equal to zero

echo $var ; // or do some processing

}



 
 
>>> More MySQL Articles          >>> More By Shikhar Kumar
 

blog comments powered by Disqus
   

MYSQL ARTICLES

- Xeround Releases Free Version of MySQL Cloud...
- Oracle Announces New MySQL Specialization
- Constant Contact Chooses SkySQL for MySQL Su...
- Revoke Statement in MySQL
- The Grant Statement in MySQL
- SuccessBricks Announces ClearDB Availability...
- Building a PHP ORM: Deploying a Blog
- TROSYS Launches Free MySQL Manager and Admin...
- Building an ORM in PHP: Domain Modeling
- Building an ORM in PHP
- MySQL Leads Open Source Market, Gets Cluster...
- Oracle Announces Milestone Release for MySQL
- How to Stop SQL Injection Attacks
- New Defragmentation Solution for SQL Server
- Comparison of MyISAM and InnoDB MySQL Databa...


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap

Dev Shed Tutorial Topics: