oop php 使用PDO将数据插入MySQL数据库的简单函数


oop php simple function to insert data into mysql database using PDO

>我是 php OOP 的新手,我尝试在 php 中创建一个函数来将数据插入数据库,但它不起作用,请帮忙。

我的职能:

public function insert($table, $fields = array(), $values = array()) {
    $sql = " INSERT INTO{$table}($fields) VALUES($values)";
    $this->_pdo->prepare ( $sql );
    return $this->_pdo->exec ( $sql );
}
这是一个

有效的OOP PHP Insert函数,它应该很容易理解,但如果你不只是问。

public function insert($table, $fields = array()) {
        $keys   = array_keys($fields);
        $values = null;
        $x      = 1;
        foreach($fields as $value) {
            $values .= "?";
            if($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }
        $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
        if(!$this->query($sql, $fields)->error()) {
            return true;
        }
        return false;
    }