I've got a couple of model classes handling a db layer, and I've got a logic error in how to hand the db connection to the query in an OO way. Class1 is a db_connect which I'm calling inside the constructor of class2 query methods:
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();
}}
But I'm getting an undefined variable error with $insert.
I am calling that layer with the following:
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);
The way I'm connecting with the constructor of the query class seems to be working but not sure which variable I need in scope to attach to the prepare/bind/execute statements?
And I do know that I should be using PDO or another ORMy type tool. Which I will, but this is more about some basic OO get/set/retrieve best practice ... thanks for your help.