php - MySQLi OOP 类插入功能不起作用

标签 php class oop mysqli

我目前正在练习 OOP,创建一个 MySQLi 类,该类至少具有基本的 MySQLi 功能(插入、选择、更新等)。这是我到目前为止所得到的:

if(!class_exists('dbc')) {
class dbc {
    public function __construct($host = host, $username = username, $password = password, $database = database) {
        // Make the constants class variables
        $this->host = host;
        $this->username = username;
        $this->password = password;
        $this->database = database;

        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);

        if($this->connection->connect_errno) {
            die('Database connection error!');
            return false;
        }
    }

    public function __deconstruct() {
        if($this->connection) {
            $this->connection->close();
        }
    }

    public function insert($table, $variables = array()) {
        if(empty($table) || empty($variables)) {
            return false;
        }

        $sql = "INSERT INTO $table ";

        $fields = array();
        $values = array();
        foreach($variables as $field => $value) {
            $fields[] = "'" . $field . "'";
            $values[] = "'" . $value . "'";
        }

        $fields = '(' . implode(', ', $fields) . ')';
        $values = '(' . implode(', ', $values) . ')';

        $sql .= $fields . ' VALUES ' . $values;

        $query = $this->connection->query($sql);

        if(!$query) {
            echo mysqli_error($this->connection);
        }

        echo $sql;
    }
}
}

如您所见,我通过配置文件中的详细信息创建连接,然后通过已建立的连接发送查询。但由于某种原因,当我尝试创建 MySQLi 插入查询时,我只是一遍又一遍地遇到相同的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''name', 'option') VALUES ('Sub Title', 'This is a test website')' at line 1

我什至回显了 sql 查询,这似乎是正确的格式:

INSERT INTO options ('name', 'option') VALUES ('Sub Title', 'This is a test website')

我花了几个小时的谷歌搜索、反复试验等,试图解决这个问题,但没有运气,而且现在是凌晨 12:30,我很累,可能错过了一些关键的东西,所以如果有人知道什么导致了这个问题,如果有解决方案等等,我们将不胜感激。

谢谢, 基隆

最佳答案

第一组括号中的列名不应加引号:

INSERT INTO options (name, option) VALUES ('Sub Title', 'This is a test website')
//                   ^^^^  ^^^^^^

尽管您可以在列名称周围使用反引号`,例如`名称`,`选项`

关于php - MySQLi OOP 类插入功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352817/

相关文章:

C++如何在OO设计中显示多维数组

php - 如何检查具有变量名称的错误包

php - Laravel:防止 updated_at 填写记录创建

php - Doctrine 2 DQL - 按精确的 ManyToMany 数组选择

java - 我的成员变量在 Eclipse 中用红色下划线表示

javascript - 使用 JavaScript 变量用 XML 数据动态填充标记

php - Mysql条件MAX或MIN依赖于另一个列值

xcode - 从另一个类调用方法,而不重新初始化它

c++ - 使用私有(private)参数调用公共(public)函数

python - 无法对符合给定条件的列中的值求和