gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:24:25 25 4
gpt4 key购买 nike

我目前正在练习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com