Jump to content

Help Required to create single function for 4 different tables


Recommended Posts

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • 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.