Pop\Data\Type\Sql::encode PHP Метод

encode() публичный статический Метод

Encode the data into its native format.
public static encode ( mixed $data, string $table = null, string $idQuote = null, integer $divide = 100 ) : string
$data mixed
$table string
$idQuote string
$divide integer
Результат string
    public static function encode($data, $table = null, $idQuote = null, $divide = 100)
    {
        $fields = array();
        foreach ($data as $ary) {
            $fields = array_keys((array) $ary);
        }
        $table = null === $table ? 'data' : $table;
        $idQuoteEnd = $idQuote == '[' ? ']' : $idQuote;
        $sql = "INSERT INTO {$idQuote}{$table}{$idQuoteEnd} ({$idQuote}" . implode("{$idQuoteEnd}, {$idQuote}", $fields) . "{$idQuoteEnd}) VALUES\n";
        $i = 1;
        foreach ($data as $key => $ary) {
            foreach ($ary as $k => $v) {
                $ary[$k] = "'" . str_replace("'", "\\'", $v) . "'";
            }
            $sql .= "(" . implode(', ', $ary) . ")";
            if ($i % $divide == 0) {
                $sql .= ";\n";
                if ($i < count($data)) {
                    $sql .= "INSERT INTO {$idQuote}{$table}{$idQuoteEnd} ({$idQuote}" . implode("{$idQuoteEnd}, {$idQuote}", $fields) . "{$idQuoteEnd}) VALUES\n";
                }
            } else {
                if ($i < count($data)) {
                    $sql .= ",\n";
                } else {
                    $sql .= ";\n";
                }
            }
            $i++;
        }
        return $sql;
    }

Usage Example

Пример #1
0
 public function testEncode()
 {
     $ary = array(array('Name' => 'Test1', 'Num' => 1), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2), array('Name' => 'Test2', 'Num' => 2));
     $s = Sql::encode($ary, null, null, 5);
     $this->assertContains('INSERT INTO data (Name, Num) VALUES', $s);
 }