I'm building a small chat page so me and my friends can have some fun. I want to save the messages, so on possible connection lost we can see the old messages, so I decided to insert them into a database using PDO, but I receive an error:
Call to a member function prepare() on null
I guess that's because I can't use the PDO that way (in a class), but I'm not very familiar with classes:
<?php
$DBH = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', '');
$DBH->exec('SET NAMES utf8');
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once(dirname(__FILE__) . '/vendor/autoload.php');
class Socket implements MessageComponentInterface {
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $connection) {
$this->clients->attach($connection);
print('Connection: ' . $connection->resourceId . "\n");
}
public function onMessage(ConnectionInterface $sender, $message) {
$STH = $DBH->prepare("INSERT INTO chats (sender, message) VALUES (:sender, :message)");
$STH->execute(array(
'sender' => $sender->resourceId,
'message' => $message,
));
foreach($this->clients as $client) {
$client->send($sender->resourceId . ': ' . $message . "\n");
}
}
public function onClose(ConnectionInterface $connection) {
//
}
public function onError(ConnectionInterface $connection, \Exception $error) {
//
}
}
$server = IoServer::factory(new HttpServer(new WsServer(new Socket())), 8080);
$server->run();
?>