3

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.

Mark Vincent Manjac
  • 507
  • 1
  • 6
  • 27

1 Answers1

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

Community
  • 1
  • 1
leggetter
  • 15,248
  • 1
  • 55
  • 61
  • $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