Search This Blog

Monday, October 22, 2012

PHP : Array to MySQL Table

I knew there has to be some way to simplify whole big process of INSERTing FORM DATA into SQL Table in less time.

Here is How?

1. Collect all form data into an array
    $flds = $_POST;
2. Check Every form data has been collected in ARRAY
print_r($flds);
If things are fine...
3. There is one more things that is to remove "submit" button field
Count Total # of Arrays
$carray = count($flds);
4. Remove "Submit" Array:
array_splice($flds,$carray);
5. If you want to add few fields with default values -- the put them in form HIDDEN FIELDS or Try this to add MANUALLY:
$flds["new_field"] = "new_field_value";
5. Write a Function to extract values from array and insert into MySQL Table
 function mysql_insert_array($table, $data) { 
            foreach ($data as $field=>$value) { 
            $fields[] = '`' . $field . '`';  
            $values[] = "'" . mysql_real_escape_string($value) . "'"; } 
         
            $field_list = join(',', $fields); 
            $value_list = join(', ', $values); 
            
            $query = mysql_query("INSERT INTO `" . $table . "` (" . $field_list . ") VALUES (" . $value_list . ")") or die('Error in Inserting from ARRAY : ' . mysql_error()); 
   return $query; 
   }
6. FINAL NAIL to Good Old Frame for "Wall of Fame" :
     mysql_insert_array("tablename",$flds);
Note: This function can be used without hesitation anywhere, where there is no 2nd table or cross table data storage. Copy code BINDAAS-ly...

Wow!!!! That's Called Music...

It is shameful, even after 8 years into PHP. Never used it. Although the concept was there at cornor of my mind for very longtime (about 5 years) --> That $_POST is an ARRAY ITSELF.

Finally, I worked my way out today for my client Yellow Cab Airport Taxi

Hope you like it...


No comments:

Post a Comment

content-wide advt