Mayank Posted September 7, 2013 Share Posted September 7, 2013 I have 4 tables A (32 columns), B (50 columns), C (25 columns), D (52 columns), I want to write a single function to insert the values in all 4 tables. How can I manage the difference in the number of columns. Quote Link to comment https://forums.phpfreaks.com/topic/281953-help-required-to-create-single-function-for-4-different-tables/ Share on other sites More sharing options...
mac_gyver Posted September 7, 2013 Share Posted September 7, 2013 you would pass the data into the function in an array, with the array containing at least the table column name/value pairs, and optionally the data type as well so that the different possibly types can be treated appropriately in the query. Quote Link to comment https://forums.phpfreaks.com/topic/281953-help-required-to-create-single-function-for-4-different-tables/#findComment-1448598 Share on other sites More sharing options...
Mayank Posted September 10, 2013 Author Share Posted September 10, 2013 Thanks for the post Mac!!! Can you explain a bit more, I'll pass the data in an array, but how it will get to know now I need to work for 32 parameters table, 50 parameters table and so on... Thanks Again!!! Quote Link to comment https://forums.phpfreaks.com/topic/281953-help-required-to-create-single-function-for-4-different-tables/#findComment-1448940 Share on other sites More sharing options...
mac_gyver Posted September 10, 2013 Share Posted September 10, 2013 your goal is to create an INSERT INTO table_name (list of column names) VALUES (corresponding list of values) query for any table/data.the basic logic would be - function db_insert($table_name, $data){ $columns = array(); $values = array(); foreach($data as $key=>$value){ $columns[] = "`$key`"; $values[] = "'$value'"; // for simplicity, treat all data as a string (numerical data should not be handled this way, actual code left as a programming exercise for you to do) - string values need to be escaped using a method appropriate to the database library you are using } $query = "INSERT INTO `$table_name` (".implode(',',$columns).") VALUES (".implode(',',$values).")"; // run the query here using a method appropriate to the database library you are using } // example usage $some_data = array('column_name_a'=>'abc','column_name_b'=>123); // repeat for all columns you want in any INSERT query db_insert('some_table_name',$some_data); Quote Link to comment https://forums.phpfreaks.com/topic/281953-help-required-to-create-single-function-for-4-different-tables/#findComment-1448988 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.