'A Fatal error: call to a member function prepare() on null happens everytime server.php is started after a message is sent.(Ratchet Websocket+MySQL)

I am new at Ratchet Websocket and currently working on a simple chat application by using Ratchet Websocket library. Using the directions on the socketo.me site, I am trying to make websockets work by using the Chat.php and Server.php provided in http://socketo.me/docs/hello-world. My goal is want to send json string and update the database in the table (update chat messages). However, fa This is the Chat.php which is the class that implements the MessageComponentInterface.

Chat class

<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
protected $clients;

 public function __construct() {
     $this->clients = new \SplObjectStorage;
 }

 public function onOpen(ConnectionInterface $conn) {
     // Store the new connection to send messages to later
     $this->clients->attach($conn);

     echo "New connection! ({$conn->resourceId})\n";
 }

 public function onMessage(ConnectionInterface $from, $msg) {
     $numRecv = count($this->clients) - 1;
     echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
         , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

     foreach ($this->clients as $client) {
         if ($from !== $client) {
             // The sender is not the receiver, send to each client connected
             $client->send($msg);
         }
     }
 }

 public function onClose(ConnectionInterface $conn) {
     // The connection is closed, remove it, as we can no longer send it messages
     $this->clients->detach($conn);

     echo "Connection {$conn->resourceId} has disconnected\n";
 }

 public function onError(ConnectionInterface $conn, \Exception $e) {
     echo "An error has occurred: {$e->getMessage()}\n";

     $conn->close();
 }
}

I added a function, so that the messages are inserted into the database.

savemessage function

public function savemessage($data)
{
    $this->connect = 'mysql:host=' . $this->db_host . 
    ';dbname=' . $this->db_name;
    $options = array(
        PDO::ATTR_PERSISTENT => true,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );
    try {
        $this->db_handler = new PDO($this->connect, $this->db_user, $this->db_pass, $options);
    } catch (PDOException $e) {
        $this->error = $e->getMessage();
        echo $this->error;
    }
    $query = "INSERT INTO chatrooms (id, uuid, msg, created_on) VALUES (default, :uuid, :msg, :created_on)";
    $this->statement = $this->db_handler->prepare($query);
    $type = PDO::PARAM_STR;
    $this->statement->bindValue(':uuid', $data['uuid'],$type);
    $this->statement->bindValue(':msg', $data['msg'],$type);
    $this->statement->bindValue(':created_on', $data['created_on'],$type);
    return ($this->statement->execute());
}    

Chat class(edited section) The function of onMessage is edited, in order to insert the data.

    ......
    $data = json_decode($msg, true);
    if ($this->savemessage($data)) {
        echo 'Saved message to DB';
    } else {
        echo 'Failed to save message';
    }

    $data['dt'] = date("d-m-Y h:i:s");

    foreach ($this->clients as $client) {
        /*
        if ($from !== $client) {
            // The sender is not the receiver, send to each client connected
            $client->send($msg);
        }*/
        if ($client !== $from) {
            $client->send($data['msg']);
        }
    }
    ......

Screenshot of error As you can see from the screenshot, the connection is successful. The json string is successfully sent. However, there is a fatal error on the prepare function.

This line of code

$this->statement = $this->db_handler->prepare($query);

I have tried to call this function from other classes.(Originally the save message function is from other classes. The entire project is in MVC structure, but the error is still the same.)

It would be greatly appreciated if anyone have any ideas about what the problem might be or how to fix it. Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source