PDOWrapper::insert PHP Метод

insert() публичный Метод

- adds a row to the specified table
public insert ( string $table, array $params = [], boolean $timestamp_this = null ) : mixed
$table string - the name of the db table we are adding row to
$params array - associative array representing the columns and their respective values
$timestamp_this boolean (Optional), if true we set date_created and date_modified values to now
Результат mixed - new primary key of inserted table, false on failure
    public function insert($table, $params = array(), $timestamp_this = null)
    {
        if (is_null($timestamp_this)) {
            $timestamp_this = self::$TIMESTAMP_WRITES;
        }
        // first we build the sql query string
        $columns_str = '(';
        $values_str = 'VALUES (';
        $add_comma = false;
        // add each parameter into the query string
        foreach ($params as $key => $val) {
            // only add comma after the first parameter has been appended
            if ($add_comma) {
                $columns_str .= ', ';
                $values_str .= ', ';
            } else {
                $add_comma = true;
            }
            // now append the parameter
            $columns_str .= "{$key}";
            $values_str .= ":{$key}";
        }
        // add the timestamp columns if neccessary
        if ($timestamp_this === true) {
            $columns_str .= ($add_comma ? ', ' : '') . 'date_created, date_modified';
            $values_str .= ($add_comma ? ', ' : '') . time() . ', ' . time();
        }
        // close the builder strings
        $columns_str .= ') ';
        $values_str .= ')';
        // build final insert string
        $sql_str = "INSERT INTO {$table} {$columns_str} {$values_str}";
        // now we attempt to write this row into the database
        try {
            $pstmt = $this->getMaster()->prepare($sql_str);
            // bind each parameter in the array
            foreach ($params as $key => $val) {
                $pstmt->bindValue(':' . $key, $val);
            }
            $pstmt->execute();
            $newID = $this->getMaster()->lastInsertId();
            // return the new id
            return $newID;
        } catch (PDOException $e) {
            if (self::$LOG_ERRORS == true) {
                error_log('DATABASE WRAPPER::' . print_r($e, true));
            }
            $this->pdo_exception = $e;
            return false;
        } catch (Exception $e) {
            if (self::$LOG_ERRORS == true) {
                error_log('DATABASE WRAPPER::' . print_r($e, true));
            }
            $this->pdo_exception = $e;
            return false;
        }
    }