catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.84k stars 1.15k forks source link

REPLACE INTO support #440

Closed hirdeshvishwdewa closed 3 years ago

hirdeshvishwdewa commented 8 years ago

Hi All,

Is there REPLACE INTO query function in medoo?? There exists a function replace() but it does something else.

If we just replace INSERT by REPLACE in insert() function here we will get our REPLACE INTO query.

Request catfan to add following method, so that it can be used same as insert()-

public function replaceinto($table, $datas)
    {

        $lastId = array();

        // Check indexed or associative array
        if (!isset($datas[ 0 ]))
        {
            $datas = array($datas);
        }

        foreach ($datas as $data)
        {

            $values = array();
            $columns = array();

            foreach ($data as $key => $value)
            {
                $columns[] = $this->column_quote($key);

                switch (gettype($value))
                {
                    case 'NULL':
                        $values[] = 'NULL';
                        break;

                    case 'array':
                        preg_match("/\(JSON\)\s*([\w]+)/i", $key, $column_match);

                        $values[] = isset($column_match[ 0 ]) ?
                            $this->quote(json_encode($value)) :
                            $this->quote(serialize($value));
                        break;

                    case 'boolean':
                        $values[] = ($value ? '1' : '0');
                        break;

                    case 'integer':
                    case 'double':
                    case 'string':
                        $values[] = $this->fn_quote($key, $value);
                        break;
                }
            }

            $this->exec('REPLACE INTO ' . $this->table_quote($table) . ' (' . implode(', ', $columns) . ') VALUES (' . implode($values, ', ') . ')');

            $lastId[] = $this->pdo->lastInsertId();
        }

        return count($lastId) > 1 ? $lastId : $lastId[ 0 ];
    }

Thanks

3zzy commented 6 years ago

+1

lacoste-sochi commented 1 year ago

Medoo is updated, but the essence is the same.

We take copy the insert method completely

And we put REPLACE INTO instead of INSERT INTO . We call the method replaceinto , and rejoice.

For Type Auto-Detection, generally huge respect to the team!!!