You have many ways.
MySQL: Using sys_exec()
.
It can be used as a Trigger
, whenever the data is added it is triggered and therefore can trigger a file, such as a PHP, this PHP sends the information via websocket.
Hex: PHP tends to be slow and added to the connection time you will have a much slower query , since it will only terminate after the websocket is completed, or you will have to do some gambiarra to execute silently , either way this will not be mentioned in EXPLAIN
, you may not know the reason the database is slow.
I found this PubNub , a company that offers websockets , which uses curl
directly using sys_eval()
, but with a "warning" that this is not recommended.
MySQL: Check the logs.
Do you know how MySQL replicas are synchronized (a master + X slaves)? One of the ways is to synchronize the master logs, it contains everything that has been changed and you can use this to see what has changed and to send information based on it. This solution is perhaps the most complex (and least clear) in my opinion, you can also use something like inotifywait
to trigger when the file is updated.
PHP: Send after commit
.
Imagine that you have a website that has a balance, transferable between users, you want to notify them when they each receive and send, for example :
mysqli_begin_transaction($con);
mysqli_autocommit($con, false);
$detalhe = mysqli_query($con, '
INSERT INTO 'pagamento_detalhe'('QuemPagou', 'QuemRecebeu', 'Valor')
VALUES ("'.$idPagou.'", "'.$idRecebeu.'", "'.$Valor.'")
');
$detalhe = mysqli_affected_rows($con) === 1;
$atualizaSaldo = mysqli_query($con, '
UPDATE usuario as Pagou, usuario as Recebeu
SET Pagou.Saldo = Pagou.Saldo - '.$Valor.', Recebeu.Saldo = Recebeu.Saldo + '.$Valor.'
WHERE Pagou.id = "'.$idPagou.'" AND Recebeu.id = "'.$idRecebeu.'"
');
$atualizaSaldo = mysqli_affected_rows($con) === 2;
if($atualizaSaldo && $detalhe){
mysqli_commit($con);
}else{
mysqli_rollback($con);
}
It would be easier to add something like this:
//...
if($atualizaSaldo && $detalhe){
mysqli_commit($con);
enviar_websocket($idPagou, 'Você enviou '.$Valor);
enviar_websocket($idRecebeu, 'Você recebeu '.$Valor);
}else{
mysqli_rollback($con);
}
Creating a function enviar_websocket
will send the websocket
to the corresponding id
with a message you define, EG. This will be sent whenever a data update occurs, but still on the PHP side rather than MySQL.