是否可以使用php创建插入方法

I'm looking for some advice where I'm using PDO and trying to insert form data into my database.

I've created a class where I'm connecting to my database through the construct, when the form is filled out, I want to use a method to accept the data to insert it into my database.

Is this possible?? Or, do I need to resolve it through a procedural method?

my insert statement looks like:

class Post extends Database
{

    public function postMessage($username, $message)
    {
        if (isset($_SERVER['POST'])){

            $connection->setAttribute(PDO::ATTR_ERRMODE, 
            PDO::ERRMODE_EXCEPTION);

            $statement = $connection->prepare("INSERT INTO messages 
            (username, message) VALUES (:user, :message)");

            $statement->bindParam(':username', $username);
            $statement->bindParam(':message', $message);

            $statement->execute();

            echo "Message has been sent";

        } else {
            exit("Need to enter a message");
        }

    }
}

Remove the if-else statement (like this):

class Post extends Database
{
    public function postMessage($username, $message)
    {
        if(!empty($username) && !empty($password))
        {
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, 
            PDO::ERRMODE_EXCEPTION);

            $statement = $connection->prepare("INSERT INTO messages 
            (username, message) VALUES (:user, :message)");

            $statement->bindParam(':username', $username);
            $statement->bindParam(':message', $message);

            if($statement->execute())
               echo "Message has been sent";
            else
               echo "Something wants wrong!";
         }
         else
         {
            echo "Please fill all fields!";
         }
    }
}

Create object and call the function:

$post = new Post;
echo $post->postMessage("John", "Hello, world");