I'm trying to use Pusher for making a real time push notification. I want to trigger the pusher when mysql data is change. Can someone help me with it? I'm new on this pusher.
Asked
Active
Viewed 2,201 times
1 Answers
3
The simplest way to to do this is to trigger an event via Pusher after you have performed the database interaction.
e.g.
// Connect and interact with database
$mysqli = new mysqli("server", "username", "password", "database_name");
$value = $_POST["activity-name"];
$stmt = $mysqli->prepare("INSERT INTO activities (column) VALUES (?)");
$stmt->bind_param("s", $value);
$stmt->execute();
// TODO: check the INSERT was successful.
$stmt->close();
$mysqli->close();
// TODO: Only trigger if the DB interaction was successful
// Create Pusher instance (assuming the Pusher library has been required)
$pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID);
// Trigger the event representing the new data that's been inserted
$pusher->trigger('activities', 'activity-created' ['name' => $value]);
If the database interact were for an UPDATE
then you can use a different event name.
$pusher->trigger('activities', 'activity-updated' ['name' => $value]);
Alternatively you could set up a database trigger and have another script execute and interact with Pusher when a change takes place. See Invoking a PHP script from a MySQL trigger
-
$stmt->close(); $mysqli->close(); // If your application crashes right here; event is never sent -> bad practice // Create Pusher instance (assuming the Pusher library has been required) $pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID); – morissette Mar 10 '17 at 16:49