Jump to content

Help Required to create single function for 4 different tables


Mayank

Recommended Posts

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.

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.