Friday, June 11, 2010

Insert queries in NULL condition

When you going to take some thing from a database, modify it and reinsert it as a new record you will find some errors.As each data records do not have full records. Some of them are null fields.So you have to validate and write dynamic queries to solve these issues.Here is the eesy PHP way.......

1.Make MySQL connection via mysql_connect(),mysql_select_db() 

 $connection mysql_connect("address_of_server","username","password"); 
 mysql_select_db("database", connection);

2.Query the data base to get needed records via mysql_query()

 $record mysql_query("SELECT * FROM table WHERE id=3;");

3.For avoid errors cast it to an array.

  $record = (Array)$record

4.Then check necessary fields for null and make the trick (to re insert it as null field)

 $name=(!empty($record ['name']) ? $record ['name'] : "NULL");
      At here it checks for the null condition and if null initialize new variable as null

5.Reinsert the data using new variables making new dynamic query.


 $result mysql_query("INSERT INTO table(id,name)VALUES(5,".$name."); ");

To deal with more than one record, combine this with foreach and mysql_num_rows($record)

  Have fun with this. eeesY

No comments:

Post a Comment