Categories: MysqlPhp

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.

Related Post

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.

View Comments

Recent Posts

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

2 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

2 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

2 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

3 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

3 months ago

Common Practices for Laravel Blade Template

in this Laravel tutorial, I will explore common practices for using the Laravel Blade template with examples. Blade is a… Read More

3 months ago

Categories