ParagonIE\EasyDB\EasyDB::insert PHP Method

insert() public method

Insert a new row to a table in a database.
public insert ( string $table, array $map ) : integer
$table string - table name
$map array - associative array of which values should be assigned to each field
return integer
    public function insert(string $table, array $map) : int
    {
        if (!empty($map)) {
            if (!$this->is1DArray($map)) {
                throw new \InvalidArgumentException('Only one-dimensional arrays are allowed.');
            }
        }
        // Begin query string
        $queryString = 'INSERT INTO ' . $this->escapeIdentifier($table) . ' (';
        $pHold = [];
        $_keys = [];
        $params = [];
        foreach ($map as $k => $v) {
            if ($v !== null) {
                $_keys[] = $k;
                if ($v === true) {
                    $pHold[] = 'TRUE';
                } elseif ($v === false) {
                    $pHold[] = 'FALSE';
                } else {
                    // When all else fails, use prepared statements:
                    $pHold[] = '?';
                    $params[] = $v;
                }
            }
        }
        // Let's make sure our keys are escaped.
        $keys = [];
        foreach ($_keys as $i => $v) {
            $keys[] = $this->escapeIdentifier($v);
        }
        // Now let's append a list of our columns.
        $queryString .= \implode(', ', $keys);
        // This is the middle piece.
        $queryString .= ') VALUES (';
        // Now let's concatenate the ? placeholders
        $queryString .= \implode(', ', $pHold);
        // Necessary to close the open ( above
        $queryString .= ');';
        return (int) $this->safeQuery($queryString, $params, \PDO::FETCH_BOTH, true);
    }