Create Dynamic SQL Insert Query in PHP and MySql

This PHP tutorial help to create dynamic sql insert query using table and data .I have taken this function reference from google search. This function is very useful when you are working model-level architecture.

In this function, the main restriction is data key value is the same as the table column name like other framework ORM.

Example of Dynamic Insert Query for MySQL Using PHP

if MySQL table has 2 column name and age. Then data array should be array('name' => 'parvez', 'age' =>'26').

The function takes two arguments one is table name where it will insert and the other is $data what will insert into the table. The $data is a key-value pair of an array and so first we will separate key and value from the data array.

Now we will implode keys and values of arrays and create a string of insert SQL.

Also Checkout other dynamic mysql query tutorials,

Source Code to create dynamic insert Query in php and Mysql

protected function build_sql_insert($table, $data) {
    $key = array_keys($data);
    $val = array_values($data);
    $sql = "INSERT INTO $table (" . implode(', ', $key) . ") "
         . "VALUES ('" . implode("', '", $val) . "')";
 
    return($sql);
}

As you can see, I have taken array keys and values into a separate PHP array and passed them to the INSERT MySQL query using PHP implode() function.

One thought on “Create Dynamic SQL Insert Query in PHP and MySql

Leave a Reply

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