Create Dynamic MySQL Record Inserter with PHP

Posted on

As a PHP programmer we always need to write INSERT statement repeatedly to insert records into database. This sometimes makes us annoyed to write same thing again and again in same script. To overcome this, we have created a generic insert script to handle all insert record by just passing array of table field name and table field values.

Here is complete code of function insertRecord() that you may use in your PHP project.
<?php
function insertRecord($table, $fields, $values, $return = false){
$newFields = "(`" . implode("`, `", $fields) . "`)";
$newValues = "('" . implode("', '", $values) . "')";
$insertRecord = mysql_query("INSERT INTO `{$table}` {$newFields} VALUES {$newValues}");
if($insertRecord){
if($return){
return mysql_insert_id();
}else{
return true;
}
}else{
return false;
}
}

The above function insertRecord() that can be used in any PHP project. The function will take four parameters. The first parameter needs the table name you’re creating the new record in. The second parameter will be the variable that contains the array of field names of the table you have chosen. The third parameter will contain the values to add into the field names in its own record. The fourth parameter is option. Adding true to it will return the last ID that MySQL auto incremented to your PHP code, so you may use it in any way you like.

Here we will learn how to use generic insertRecord() function:
$tblFields = array("topic_id", "topic_userid", "topic_title", "topic_content", "topic_date");
$tblValues = array(NULL, $user_id, $topic_title, $topic_content, $topic_date);
$insert = insertRecord("topics", $tblFields, $tblValues, true);
if($insert){
echo "Record Inserted Successfully!";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *