Jump to content

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.

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!!!

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

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