我有几个模型类处理数据库层,并且在如何以 OO 方式将数据库连接传递给查询时出现逻辑错误。Class1 是一个 db_connect,我在 class2 查询方法的构造函数中调用它:
class db {
public $host = 'localhost';
public $username = 'root';
public $password = '';
public $database = 'molecule';
public $mysqli = '';
function __construct() {
$mysqli = new mysqli($this->host, $this->username, $this->password, $this->database);
if (mysqli_connect_errno()) {
printf("Database Connection failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli;
}
}
class nodeModel {
public $node;
public $node_name;
public $node_link;
public $node_comment;
public $mysqli;
function __construct() {
$mysqli = new db;
return $mysqli;
}
public $insert;
public $insert_id;
function insertNode($node_name, $node_link, $node_comment) {
$this->insert = $insert;
$this->insert = $mysqli->prepare("INSERT INTO node(node_name, name_link, node_comment) VALUES (?, ?, ?)");
$this->insert->bind_param("sss", $this->node_name, $this->node_link, $this->node_comment);
if($this->insert->execute()) {
$this->insert_id = $mysqli->insert_id;
}
return $this->insert_id;
print_r($this->insert_id);
$this->insert->close();
}}
但是我收到 $insert 的未定义变量错误。
我用以下内容调用该层:
include 'node_model.php';
$dbTest = new nodeModel;
$node_name = 'My Node Title';
$node_link = 'My Node Link';
$node_comment = 'My Node Comment. This one should be longer so I will write more stuff';
$dbTest->insertNode($node_name, $node_link, $node_comment);
我与查询类的构造函数连接的方式似乎正在工作,但不确定我需要在范围内将哪个变量附加到准备/绑定/执行语句?
而且我知道我应该使用 PDO 或其他 ORMy 类型的工具。我会的,但这更多的是关于一些基本的 OO 获取/设置/检索最佳实践......感谢您的帮助。