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.
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,
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.
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
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
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More
View Comments
hi an actual example using th whole function would be useful