Coder Social home page Coder Social logo

laravelbatch's Introduction

Laravel BATCH (BULK)

Insert and update batch (bulk) in laravel

License Latest Stable Version Total Downloads Daily Downloads

Install

composer require mavinoo/laravel-batch

Service Provider

file app.php in array providers :

Mavinoo\Batch\BatchServiceProvider::class,

Aliases

file app.php in array aliases :

'Batch' => Mavinoo\Batch\BatchFacade::class,

Example Update 1

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'status' => 'active',
         'nickname' => 'Mohammad'
     ] ,
     [
         'id' => 5,
         'status' => 'deactive',
         'nickname' => 'Ghanbari'
     ] ,
];
$index = 'id';

Batch::update($userInstance, $value, $index);

Example Update 2

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'status' => 'active'
     ],
     [
         'id' => 5,
         'status' => 'deactive',
         'nickname' => 'Ghanbari'
     ],
     [
         'id' => 10,
         'status' => 'active',
         'date' => Carbon::now()
     ],
     [
         'id' => 11,
         'username' => 'mavinoo'
     ]
];
$index = 'id';

Batch::update($userInstance, $value, $index);

Example Increment / Decrement

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'balance' => ['+', 500] // Add
     ] ,
     [
         'id' => 2,
         'balance' => ['-', 200] // Subtract
     ] ,
     [
         'id' => 3,
         'balance' => ['*', 5] // Multiply
     ] ,
     [
         'id' => 4,
         'balance' => ['/', 2] // Divide
     ] ,
     [
         'id' => 5,
         'balance' => ['%', 2] // Modulo
     ] ,
];
$index = 'id';

Batch::update($userInstance, $value, $index);

Example Insert

use App\Models\User;

$userInstance = new User;
$columns = [
     'firstName',
     'lastName',
     'email',
     'isActive',
     'status',
];
$values = [
     [
         'Mohammad',
         'Ghanbari',
         '[email protected]',
         '1',
         '0',
     ] ,
     [
         'Saeed',
         'Mohammadi',
         '[email protected]',
         '1',
         '0',
     ] ,
     [
         'Avin',
         'Ghanbari',
         '[email protected]',
         '1',
         '0',
     ] ,
];
$batchSize = 500; // insert 500 (default), 100 minimum rows in one query

$result = Batch::insert($userInstance, $columns, $values, $batchSize);
// result : false or array

sample array result:
Array
(
    [totalRows]  => 384
    [totalBatch] => 500
    [totalQuery] => 1
)

Example called from model

Add HasBatch trait into model:

namespace App\Models;

use Mavinoo\Batch\Traits\HasBatch;

class User extends Model
{
    use HasBatch;
}

And call batchUpdate() or batchInsert() from model:

use App\Models\User;

// ex: update
User::batchUpdate($value, $index);

// ex: insert
User::batchInsert($columns, $values, $batchSize);

Helper batch()

// ex: update

$result = batch()->update($userInstance, $value, $index);


// ex: insert

$result = batch()->insert($userInstance, $columns, $values, $batchSize);

Tests

If you don't have phpunit installed on your project, first run composer require phpunit/phpunit

In the root of your laravel app, run ./vendor/bin/phpunit ./vendor/mavinoo/laravel-batch/tests

Donate

USDT Address: 0x98410956169cdd00a43fe895303bdca096f37062

laravelbatch's People

Contributors

albertcht avatar alielmajdaoui avatar arnal1 avatar bearth avatar bhaveshdaswani93 avatar bhushan avatar bleepblorb avatar cong08 avatar faenir avatar gavrisimo avatar goszowski avatar hilbertgilbertson avatar ibrahim-sakr avatar jadenjoy avatar joaofscruz avatar jonathanm10 avatar lancepioch avatar lloricode avatar lorvent avatar madaolex avatar mavinoo avatar mehmetbeyhz avatar pezhvak avatar s-patompong avatar sasokovacic avatar saurav90 avatar viest avatar walterwoshid avatar ycs77 avatar yuzurus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

laravelbatch's Issues

json Invalid JSON text: "Invalid encoding in string."

public static function mysql_escape($fieldValue)
  {
      if (is_array($fieldValue)) {
          return array_map(__METHOD__, $fieldValue);
      }

      if (is_bool($fieldValue)) {
          return (int)$fieldValue;
      }

      if (self::is_json($fieldValue)) {
           return self::safeJson($fieldValue);
      }

      if (!empty($fieldValue) && is_string($fieldValue)) {
          return str_replace(
              ['\\', "\0", "\n", "\r", "'", '"', "\x1a"],
              ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'],
              $fieldValue
          );
      }

      return $fieldValue;
  }

replace

 public static function mysql_escape($fieldValue)
    {
        if (is_array($fieldValue)) {
            return array_map(__METHOD__, $fieldValue);
        }

        if (is_bool($fieldValue)) {
            return (int)$fieldValue;
        }

        if (self::is_json($fieldValue)) {
             fieldValue = self::safeJson($fieldValue);
        }

        if (!empty($fieldValue) && is_string($fieldValue)) {
            return str_replace(
                ['\\', "\0", "\n", "\r", "'", '"', "\x1a"],
                ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'],
                $fieldValue
            );
        }

        return $fieldValue;
    }

note: The Json field may contain special characters of mysql, which should be handled again, not just the string type

Call to undefined method

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to undefined method Mavinoo\LaravelBatch\LaravelBatchFacade::update()

I am receiving the error above even after registering the package in app.php. I have used this package before but it was version one. I am wondering what the correct course of action would be to resolve the issue.

Increment multiple values?

Is there something available to increment multiple values like this?

$userInstance = new \App\Models\User;
$values = [
    [
        'id' => 4,
        'balance' => 'balance + 5',
    ],
    [
        'id' => 5,
        'balance' => \DB::raw('balance + 200'), // This works for the "->update" method
    ]
];
$index = 'id';
Batch::update($userInstance, $values, $index);

Class 'Batch' not found

I have added to aliases and providers in app.php but it does not seem to work.

My code:

public function storeBanks($request) {
	$selected = $this->getListOfSelectedBanksIds();
	return Batch::update('bank_school', $this->createUpdateBankObject($request, $selected));
}

LaravelBatchServiceProvider class not found in ProviderRepository file

Hi Team,

After composer update we are getting following error.

FYI - we are using dev-master version

2020-05-31 19:19:01] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Mavinoo\LaravelBatch\LaravelBatchServiceProvider' not found' in /app/server/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php:146
Stack trace:

json value convert error

src/Common/Common.php

protected static function safeJson($jsonData, $asArray = false)
{
    $jsonData     = json_decode($jsonData, true);
    $safeJsonData = [];
    if (!is_array($jsonData)) {
        return $jsonData;
    }
    foreach ($jsonData as $key => $value) {
        if (self::is_json($value)) {
            $safeJsonData[$key] = self::safeJson($value, true);
            if (gettype($safeJsonData[$key]) != gettype($value)) {
                $safeJsonData[$key] = $value;
            }
        } elseif (is_string($value)) {
            $safeJsonData[$key] = self::safeJsonString($value);
        } elseif (is_array($value)) {
            $safeJsonData[$key] = self::safeJson(json_encode($value), true);
        } else {
            $safeJsonData[$key] = $value;
        }
    }
    return $asArray ? $safeJsonData : json_encode($safeJsonData);
}

Using SQL functions not possible

Hi!

Nice package, but i have one problem. I'm trying to use MySQL spatial functions for update and the line below add quatation marks to the function and therefore it won't evaluate. Is it possible to change the code so using sql functions is also possible?

$value = (is_null($val[$field]) ? 'NULL' : '"' . Helpers::mysql_escape($val[$field]) . '"');

operator does not exist: ` character varying when using SQL-Server

when using SQLServer throw this error

[Illuminate\Database\QueryException]
"SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '`'. (SQL: UPDATE ...

so I need to remove backtick symbol from vendor\mavinoo\laravel-batch\src\Batch.php

from

if ($driver == 'pgsql' )
$final[$field][] = 'WHEN ' . $index . ' = '' . $val[$index] . '' THEN ' . $value . ' ';


to

if ($driver == 'pgsql' || $driver == 'sqlsrv')
$final[$field][] = 'WHEN ' . $index . ' = '' . $val[$index] . '' THEN ' . $value . ' ';

while the type of index is string, update error

line 65 in src/LaravelBatch.php
$query = 'UPDATE ' . $table . ' SET '. substr($cases, 0, -2) . ' WHERE ' . $index . ' IN('.implode(',', $ids).')';

while the index type is string

also, the value string should escaped like this:

DB::connection()->getPdo()->quote($val[$field]))

NULL gets replaced with ""

I believe the update function replaces null values with "" (an empty string), which leads to sql errors; can't assign "" to an INT column, for example.

How to get inserted IDs

hello. Thanks for this library!
I need a way to verify if the rows I inserted really got inserted. Currently, it only returns the following:

{
totalRows: 2,
totalBatch: 100,
totalQuery: 1
}

Is there a way to return the inserted IDs?

How do i use the service providers

I am relatively new to laravel so really don't know how to use this providers well. i have been able to install the dependencies but don't know how to use Mavinoo\UpdateBatch\UpdateBatchServiceProvider::class or
'UpdateBatch' => Mavinoo\UpdateBatch\UpdateBatchFacade::class,

Syntax error !

I got this error while updating a table:

SQLSTATE[42601]: Syntax error: 7 ERROR: error de sintaxis en o cerca de «»`

im creating an array for each row i want to update like this:

private function customer_array($ctm, $id, $status)
  {

    $array = [
      'code' => rtrim($ctm->co_cli),
      'type' => rtrim($ctm->tip_cli),
      'name' => utf8_encode(strtoupper($ctm->cli_des)),
      'rif' => str_replace('-', '', $ctm->rif),
      'email' => utf8_encode(strtolower($ctm->email)),
      'address1' => utf8_encode(strtoupper($ctm->direc1)),
      'address2' => utf8_encode(strtoupper($ctm->dir_ent2)),
      'phones' => $ctm->telefonos,
      'fax' => $ctm->fax,
      'status' => $status,
      'comment' => utf8_encode($ctm->comentario),
      'responsable' => utf8_encode($ctm->respons),
      'taxpayer' => $ctm->contrib,
      'credit' => $ctm->mont_cre,
      'coin' => rtrim($ctm->co_mone),
      'segment' => $ctm->co_seg,
      'company_id' => $id,
      'payment_condition_name' => $ctm->cond_pag,
      'seller_code' => rtrim($ctm->co_ven),
      'zone_name' => $ctm->co_zon,
    ];

    return $array;

  } // customer_array

Because of the size of my data (nearly 5k rows) y use chunks to update them like this:

$chunk_customers = array_chunk($act_customers_array, 3);
    foreach ($chunk_customers as $chunk) {
      // Tabla que se actualiza
      $table = 'customers';
      // Valores para actualizar
      $value = $chunk;
      // Indice de referencia
      $index = 'code';
      // Actualizacion
      Batch::update($table, $value, $index);
    }

But yes... I keep getting this error over and over again. Any ideas ?

Im ussing Laravel 5.6 and PostgreSQL !

Btw, does this works with PostgreSQL?

PostgreSQL Json Field

A problem occurs when the column type is json.

data =
json_encode(['status' => 'ok' , 'message' => 'test']);

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type json

ErrorException: Non-static method Mavinoo\LaravelBatch\Batch::update() should not be called statically

I have Laravel 5.5.28

I did the following:

  1. composer require mavinoo/laravel-batch:dev-master
  2. In config/app.php, providers array, added: Mavinoo\LaravelBatch\LaravelBatchServiceProvider::class,
  3. In config/app.php, aliases array, added: 'Batch' => Mavinoo\LaravelBatch\LaravelBatchFacade::class,
  4. In my job I have included this on top: use Mavinoo\LaravelBatch\Batch;
  5. In the same job file I then used it like: Batch::update('datatable', $data, 'id');

But I get the following error:

ErrorException: Non-static method Mavinoo\LaravelBatch\Batch::update() should not be called statically

I even tried taking step 4 out, but I got the same error

What's wrong?

Does not work for pgsql ( postgresql )

the solution works for mysql but not for pgsql, there is query error for pgsql, I have updated code pgsql as well, please update if you think this is ok

update function code in LaravelBatch.php file

`
public function update(Model $table, array $values, string $index = null, bool $raw = false)
{
$final = [];
$ids = [];

    if (!count($values)) {
        return false;
    }

    if (!isset($index) || empty($index)) {
        $index = $table->getKeyName();
    }

    foreach ($values as $key => $val) {
        $ids[] = $val[$index];
        foreach (array_keys($val) as $field) {
            if ($field !== $index) {
                $finalField = $raw ? Common::mysql_escape($val[$field]) : "'" . Common::mysql_escape($val[$field]) . "'";
                $value = (is_null($val[$field]) ? 'NULL' : $finalField);
                $final[$field][] = 'WHEN "' . $index . '" = \'' . $val[$index] . '\' THEN ' . $value . ' ';
            }
        }
    }

    $connection = config('database.default');

    $driver = config("database.connections.{$connection}.driver");

    if ( $driver == 'pgsql' ){

        $cases = '';
        foreach ($final as $k => $v) {
            $cases .= '"' . $k . '" = (CASE ' . implode("\n", $v) . "\n"
                . 'ELSE "' . $k . '" END), ';
        }

         $query = "UPDATE \"" . $this->getFullTableName($table) . '" SET ' . substr($cases, 0, -2) . " WHERE \"$index\" IN('" . implode("','", $ids) . "');";

    }else{

        $cases = '';
        foreach ($final as $k => $v) {
            $cases .= '`' . $k . '` = (CASE ' . implode("\n", $v) . "\n"
                . 'ELSE `' . $k . '` END), ';
        }

         $query = "UPDATE `" . $this->getFullTableName($table) . "` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . '"' . implode('","', $ids) . '"' . ");";

    }
    

    return $this->db->connection($this->getConnectionName($table))->update($query);
}`

Syntax error ERROR: syntax error at or near

I get some errors while i try to update records
here is my array
$array = [ [ 'flm' => 'alexis rozaline', 'card_type' => 'MasterCard', 'card_number' => '.....', 'id' => 1 ] ]
\batch()->update(new BankDetail(), $request->get('bank_details'), 'id');
how can i resolve this?

creates invalid query with quotes in json

mysql requires \\ to escape " in a query

the correct query should be:

UPDATE `test_rows`
SET `test_column` = '{"name":"some \\"quoted\\" word"}' 
WHERE `id` = 1;

but running this:

$data = [
 "name" => 'some "quoted" word'
];

$updates= [[
'id' => 1,
'test_column' => json_encode($data)
]];

batch()->update(new TestRow(), $updates, 'id');

results in this (invalid) query:

UPDATE `test_rows`
SET `test_column` = '{"name":"some \"quoted\" word"}' 
WHERE `id` = 1;

Another concern: The code uses string concatenation to create the when then query. Isn't this a risk for SQL injections?
Why doesn't it a parameterized query?

Facade doesn't seem to work

At least with 5.5 - so i needed to set it like:

use Mavinoo\LaravelBatch\LaravelBatchFacade as Batch;

or else when Batch::update is called goes to ErrorException: Non-static method Mavinoo\LaravelBatch\Batch::update() should not be called statically

Generally it'sgood practice to put the facade in namespace/folder Facade and the class name to be the same as the facade.

Just check most of the other packages.

File name and Class name

File "LaravelBatch" has another name at class name "Batch" then i got error

Class 'Mavinoo\LaravelBatch\Batch' not found

json_encode convert UTF-8 strings to hexadecimal entities?

Json current: {"title":"Áo thun trắng xanh đen 1231","description":"Áo thun trắng xanh đen 12345"}
After update Batch: {"title":"u00c1o thun tru1eafng xanh u0111en 1231","description":"u00c1o thun tru1eafng xanh u0111en 12345"}

Too few arguments to function

screenshot_20190221_184032

Sorry guys, but I have a big problem, in the last update I found this error in all the code that I used with its amazing package, I would love to fix it as fast as possible, help me please.

in my Code :

$columns = [
'a',
'b',
'c',
];
$batch = new Batch
$batch->insert('polls_schedulers_areas', $columns, $data, 200);

TODOs

we can add todos like

Orchestra should be used for writing tests..
contracts models folder structure is not followed..
etc.

I'll send you PR for that as well .. :) happy coding.

Nice package

Does this cover uses cases where you want to update over 1 million rows (tracking the results/timestamps is not needed)

2.1.5 / Laravel Framework 6.18.13

Symfony\Component\Debug\Exception\FatalThrowableError : Class 'Mavinoo\LaravelBatch\Batch' not found

at /var/www/html/Admin_gow/admin.backuped.site/vendor/mavinoo/laravel-batch/src/LaravelBatchServiceProvider.php:16
12| */
13| public function register()
14| {
15| $this->app->bind('LaravelBatch', function ($app){

16| return new Batch($app->make(DatabaseManager::class));
17| });
18| }
19| }
20|

Exception trace:

1 Mavinoo\LaravelBatch\LaravelBatchServiceProvider::Mavinoo\LaravelBatch{closure}(Object(Illuminate\Foundation\Application), [])
/var/www/html/Admin_gow/admin.backuped.site/vendor/laravel/framework/src/Illuminate/Container/Container.php:799

2 Illuminate\Container\Container::build(Object(Closure))
/var/www/html/Admin_gow/admin.backuped.site/vendor/laravel/framework/src/Illuminate/Container/Container.php:681

Please use the argument -v to see more details.
Script @php artisan ide-helper:generate handling the post-update-cmd event returned with error code 1

Publish a new release with Batch problem solved

{
    "message": "Class 'Mavinoo\\LaravelBatch\\Batch' not found",
    "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
    "file": "/home/vagrant/code/xxxxxxx-core/vendor/mavinoo/laravel-batch/src/LaravelBatchServiceProvider.php",
    "line": 16
....
}

I saw that you have fixed the "Batch" class problem on the ServiceProvider in the master branch. Can you publish a new release with this fix so we can establish a fixed version for our projects?

Thanks.

Add new where condition???

Hi. How to??
$product_model = new Product;
$index = 'id';
$value = [
['id' => 1,'count' => 5],
['id' => 2,'count' => 3],
];

Batch::update($product_model , $value, $index);
i want add new condition in Product model.
Product where only show_index = 1(products table column) Batch::update($product_model , $value, $index);
Please help me

How set NULL?

I have:

[ [ "id" => "40142" "invoice_number" => null ], [ "id" => "40108" "invoice_number" => "555" ] ]

Case with null - don't work. How can i insert null in batch update process?

Issue in Bulk Update

Hey I'm trying to bulk update a model but I'm facing this issue

"Class Mavinoo\Batch\Batch contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Mavinoo\Batch\BatchInterface::updateWithTwoIndex)"
trace: []

This is my code

$audioInstance = new Audio;
            $value = $record['audios'];
            $index = 'id';
           
            batch()->update($audioInstance, $value, `$index);`

Using Laravel 6 !

How to get updated instance

use App\Models\User;

$userInstance = new User;
$value = [
     [
         'id' => 1,
         'status' => 'active',
         'nickname' => 'Mohammad'
     ] ,
     [
         'id' => 5,
         'status' => 'deactive',
         'nickname' => 'Ghanbari'
     ] ,
];
$index = 'id';
Batch::update($userInstance, $value, $index);

After Batch::update, I want to access updated objects., like this:

$updatedUser=Batch::update($userInstance, $value, $index);
$updatedUser->where('country','UK')->get();

But $updatedUser is a total number of updated array, so what can I do?
Thank you~

Need testing

This library provides very cool features, but it is rather hard to adopt it in production use without any tests.

FatalThrowableError

I got this error after registering in app.php providers and aliases:
Class 'App\Http\Controllers\Batch' not found

operator does not exist: ` character varying when using postgres

when using postgres throw this error

[Illuminate\Database\QueryException]
  SQLSTATE[42883]: Undefined function: 7 ERROR:  operator does not exist: ` character varying
  LINE 1: ..."old_setting" SET "video_profil_url" = (CASE WHEN `peg_nip` ...

so I need to remove backtick symbol from vendor\mavinoo\laravel-batch\src\Batch.php

from

$final[$field][] = 'WHEN `' . $index . '` = \'' . $val[$index] . '\' THEN ' . $value . ' ';
```

to

```
$final[$field][] = 'WHEN ' . $index . ' = \'' . $val[$index] . '\' THEN ' . $value . ' ';
```

Call to undefined function Mavinoo\Batch\now() in Batch.php line 242

Hi there,

This package used to work fine for version 2.1, but I have recently run into the following error.

I have tried to install version 2.2 but I still getting the following error that the following function is undefined. now().

When I tried to update now()->format($table->getDateFormat()) to date($table->getDateFormat()) on line 67 and 242 of Batch.php it seems to work fine. Is this a solution as the database entries looks good.

Index wrapping issue

Hello.

$final[$field][] = 'WHEN "' . $index . '" = \'' . $val[$index] . '\' THEN ' . $value . ' ';

In Batch.php line number 75 the index is not properly wrapped for MySQL.

$final[$field][] = 'WHEN "' . $index . '" = \'' . $val[$index] . '\' THEN ' . $value . ' ';

Should be:

$final[$field][] = 'WHEN `' . $index . '` = \'' . $val[$index] . '\' THEN ' . $value . ' ';

It was working in previous versions but seems like recent commits have broken this feature, can you double-check it?

Regards.

Problems when updating strings starting with +

Latest release 2.2.4 has broken our build, when updating phone numbers like +420111222333, it treats this string as if increment is wanted.

I think, there should be optional parameter to enable the increment / decrement function and has it disabled by default.

Update only on integer keys?

Hi!

There is one limitation in your function updateMultipleRows, it works only if $index is integer.
But if you use instead of

$query = "UPDATE `$table` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . implode(',', $ids) . ");";

this:

$query = "UPDATE `$table` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . '"' . implode('","', $ids) . '"' . ");";

you can use strings as $index too.

I use this almost two months now, no crashes or errors.

Not compatible Composer v2

Deprecation Notice: Class Mavinoo\LaravelBatch\Batch located in ./vendor/mavinoo/laravel-batch/src/LaravelBatch.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0

json

public static function mysql_escape($fieldValue)
  {
      if (is_array($fieldValue)) {
          return array_map(__METHOD__, $fieldValue);
      }

      if (is_bool($fieldValue)) {
          return (int)$fieldValue;
      }

      if (self::is_json($fieldValue)) {
           return self::safeJson($fieldValue);
      }

      if (!empty($fieldValue) && is_string($fieldValue)) {
          return str_replace(
              ['\\', "\0", "\n", "\r", "'", '"', "\x1a"],
              ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'],
              $fieldValue
          );
      }

      return $fieldValue;
  }

replace

 public static function mysql_escape($fieldValue)
    {
        if (is_array($fieldValue)) {
            return array_map(__METHOD__, $fieldValue);
        }

        if (is_bool($fieldValue)) {
            return (int)$fieldValue;
        }

        if (self::is_json($fieldValue)) {
             fieldValue = self::safeJson($fieldValue);
        }

        if (!empty($fieldValue) && is_string($fieldValue)) {
            return str_replace(
                ['\\', "\0", "\n", "\r", "'", '"', "\x1a"],
                ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'],
                $fieldValue
            );
        }

        return $fieldValue;
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.