I'm currently learning PHP and I'm new to OOP. I'm trying to create an object to handle MySQL queries and connections.
This is what I've created so far:
class MySQLDatabase {
private $connection;
function __construct() {
$this->open_connection();
}
public function open_connection() {
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()) {
die(
"Database connection failed: " . mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
public function close_connection() {
if(isset($this->connection)) {
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$cleaned_sql = mysqli::real_escape_string($sql);
$result = mysqli_query($this->connection, $cleaned_sql);
$this->confirm_query($result);
return $result;
}
public function mysql_prep($string) {
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
private function confirm_query($result) {
if (!$result) {
die("Database query failed.");
}
}
}
And on the public-facing side (doing a test to make sure things work as expected):
$sql = "INSERT INTO users (id, username, password, first_name, last_name) ";
$sql .= "VALUES (1, 'jbloggs', 'secretpwd', 'Joe', 'Bloggs')";
$result = $database->query($sql);
Currently, I just get the output of: Database query failed.
The issue seems to be something to do with my mysql_prep function, as when I remove that all works fine.
Any advice is greatly welcomed.
Thanks in advance! Alex.