我目前正在练习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插入查询时,我只是一遍又一遍地收到相同的错误:
您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本对应的手册,了解在"名称"、"选项"附近使用的正确语法(第 1 行的值("副标题"、"这是一个测试网站"(">
我什至回显了sql查询,这似乎是正确的格式:
插入选项(">名称"、"选项"(值("副标题"、"这是一个测试网站"(
我花了几个小时的谷歌搜索,反复试验等,试图解决这个问题,但没有运气,因为现在是凌晨12:30,我很累,可能错过了一些关键的东西,所以如果有人知道是什么导致了这个问题,它将不胜感激的解决方案,等等。
谢谢基隆
第一组括号中的列名不应用引号引起来:
INSERT INTO options (name, option) VALUES ('Sub Title', 'This is a test website')
// ^^^^ ^^^^^^
尽管您可以在列名称周围使用反引号`
例如 `name`, `option`
.
您的连接肯定不起作用,因为您缺少参数名称前面这 4 行的$
$this->host = host;
$this->username = username;
$this->password = password;
$this->database = database;
应该是
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
此外,您用于类解构器的名称不正确,它应该是
public function __destruct() () {
您的不会导致错误,但它不会以您的名字在类销毁时自动运行。
@Marty关于在查询语法中使用反引号而不是单引号是正确的,但我看不出如何根据我提到的第一个错误建立连接,因此您如何报告合理的 SQL 错误,但是可能正在发生的事情从您向我们展示的代码中并不明显。