Trying to make the switch over to OOP PHP as opposed to my current approach of having a whole load of PHP code in all of my pages.
I've thrown something together which takes a post title, content and status and stores it in a simple database.
I just want to know if I have the right idea or if I'm way off - is it worth me carrying on taking this approach on it?
<?php
$conn = new mysqli('127.0.0.1','root','','admin');
class post {
private $title;
private $content;
private $status;
private $errors;
private $check;
function __construct(){
if(isset($_POST) && !empty($_POST)){
if(empty($_POST['title'])){
$this->errors[] = "Title is required";
}
if(empty($_POST['content'])){
$this->errors[] = "Content is required";
}
if(empty($_POST['status'])){
$this->errors[] = "Status is required";
}
if(empty($this->errors)){
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->status = $_POST['status'];
$this->check = true;
} else {
echo "<pre>";
var_dump($this->errors);
echo "</pre>";
}
}
}
function submit(){
if($this->check){
global $conn;
if($conn->connect_error){
die("Connection error: " . $conn->connect_error);
};
$stmt = $conn->prepare("INSERT INTO posts (title, content, status) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $this->title, $this->content, $this->status);
if($stmt->execute()){
echo "Post added succesfully";
} else {
echo "<pre>";
var_dump($stmt);
echo "</pre>";
}
};
}
};
?>