我目前正在练习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服务器版本相对应的手册,以获得正确的语法,以便使用“' name',' option')VALUES(' Sub Title') ,'这是一个测试网站')'在第1行
我甚至回应了sql查询,它似乎是正确的格式:
INSERT INTO选项('名称','选项')价值观('子标题','这是一个测试网站')
我花了几个小时的谷歌搜索,试验和错误等,试图解决这个问题,没有运气,因为它是12点30分,我很累,可能会遗漏一些关键的东西,如果有人知道造成这个问题的原因,那么对于解决方案等,我们将非常感激。
谢谢, 基隆
答案 0 :(得分:3)
您的连接肯定无法正常工作,因为您错过了参数名称前面这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错误从你向我们展示的代码中可能发生的事情并不明显。
答案 1 :(得分:2)
不应引用第一组括号中的列名:
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
addQuiz[counter] = scoreInput;
counter++;
}
虽然您可以在列名称周围使用反引号INSERT INTO options (name, option) VALUES ('Sub Title', 'This is a test website')
// ^^^^ ^^^^^^
,例如`
。