Php

Create Dynamic SQL Update Query in PHP and MySqli

Previously, I have described how to Create Dynamic Insert SQL script Using PHP. Let’s create a dynamic update SQL query based on data and table name.

We’ll create a method to update a row data into the MySQL table, You can use this method into the foreach method to create a dynamic update query.

Simple MySQL Update Query Example

Create build_sql_update() a php method into the PHP file or application.

if the table has 2 columns, one is the name and another column is age,Then data array should be as like below:

Related Post
array('name' => 'parvez', 'age' => '26')

We will define a method as follows :

function build_sql_update($table, $data, $where)

The function takes three arguments:

  1. The first one is the table name where it will insert
  2. $data what will insert. The $data is a key value pair of array.
  3. The third one is the Where condition and so first we will separate key and value from data array. Now we will implode key and values of arrays with where condition and create a string of update sql.

Checkout other dynamic MySQL query tutorials,

Full Source Code:

/* function to build SQL UPDATE string */function build_sql_update($table, $data, $where)
{
    $cols = array();

    foreach($data as $key=>$val) {
        $cols[] = "$key = '$val'";
    }
    $sql = "UPDATE $table SET " . implode(', ', $cols) . " WHERE $where";

    return($sql);
}

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

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

2 months ago

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

8 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

8 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

9 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

9 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

9 months ago

Categories