Perform a sound on another screen when a new record is inserted

Asked

Viewed 428 times

0

Good morning to all!

Good! I would like a great help from you. I am trying to make a Call panel of patients very simple for when the doctor is in the office see a table of patients and click the desired name and in the reception room appear his name and play a sound. At the moment I can only make it play a sound on the PC that is called that would be the doctor, because it would not be ideal since I would have to put sound boxes outside for each office.

This is my code:

**db.php**

<?php

  $servidor = "localhost";
  $usuario= "root";
  $password = "";
  $db = "painel";

  $conexao = new mysqli($servidor, $usuario, $password, $db);

?>

**chamar.php** 

<?php
  include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
	<title>CHAMAR CLIENTE</title>
	<link rel="stylesheet" type="text/css" href="estilos.css">
</head>
<body>

	<div id="conteudo">

		<form method="POST" action="chamar.php">
			<input type="text" name="nome">			
			<input id="id2" type="submit" name="enviar" value="Chamar Paciente" 
            onclick="ajax();">

		</form>

		<?php
			if (isset($_POST['enviar'])) {
				
				$nome = $_POST['nome'];

				$consulta = "INSERT INTO chamar (nome) VALUES ('$nome')";

				$executar = $conexao->query($consulta);

				if ($executar) {
					//EXECUTA O SOM QUANDO É INSERIDO UM REGISTRO
					echo "<embed loop='false' src='beep.mp3' hidden='true' 
                    autoplay='true'>";
				}

			}
		?>

	</div>

</body>
</html>


**index.php**

<?php
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
	<title>PAINEL DE CHAMADA</title>
	<link rel="stylesheet" type="text/css" href="estilos.css">

	<script type="text/javascript">
		function ajax(){
			var req = new XMLHttpRequest();

			req.onreadystatechange = function(){
				if (req.readyState == 4 && req.status == 200) {
					document.getElementById('chamar').innerHTML = req.responseText;					
				}
			}
					
			req.open('GET', 'painel.php', true);
			req.send();
		}

		setInterval(function(){ajax();}, 3000);
	</script>

</head>
<body>

	<div id="conteudo">
		<div id="div-chamar">
			<div id="chamar"></div>
		</div>

		<?php

			$consulta = "SELECT * FROM chamar";

					$executar = $conexao->query($consulta);

					if ($executar) {
						//SÓ EXECUTA O SOM QUANDO É ATUALIZA A PÁGINA
						echo "<embed loop='false' src='beep.mp3' hidden='true' 
                        autoplay='true'>";
					}

		?>

	</div>

</body>
</html>


**painel.php**

<?php
	include "db.php";
	
	$consulta = "SELECT * FROM chamar ORDER BY id DESC";
	$executar = $conexao->query($consulta); 
	$chamar = $executar->fetch_array();


?>
<h1 id="prova" class="mudar" style="color: #1C62C4; font-size: 80px;"><?php echo $chamar['nome']; ?></h1>

Agradeço desde já!!!

  • can send the structure of the bank so I can replicate here and make a test?

1 answer

0


Basically you will need a page that looks at the table call for

then modified the php panel. to capture the necessary data and return it in JSON:

<?php
    include "db.php";

    //ARMAZENA O TOTAL
    $consulta = "SELECT * FROM chamar ";
    $executar = $conexao->query($consulta); 
    $total = mysqli_num_rows($executar);

    //SELECIONA APENAS OS 6 ULTIMOS
    $sql = "SELECT * FROM chamar ORDER BY id DESC LIMIT 6";
    $exec = $conexao->query($sql); 
    $ultimos = array();
    $i = 0;

    while($chamar = $exec->fetch_array()){
        //eis o proximo
        if($i==0){
            $proximo = $chamar['nome'];
        }else{

            // forma os 5 ultimos
            array_push($ultimos,
                array('nome' => $chamar['nome'])
            ); 
            //para pegar mais que 5, aumente o limit no $sql;
        }
        $i++;
    }

    echo json_encode(
        [
            'total' => $total, //quantos nomes foram chamados
            'proximo' => $proximo, // nome do proximo
            'ultimos' => $ultimos // array contendo o nome dos 5 ultimos
        ]
    );

?>

I created a page called painel_exibe.php which will use the.php panel to display the data:

<style>
#painel{
    font-family:"Arial";
    width:500px;
    margin:0 auto;
    border: 1px solid #eee;
    padding: 16px;
}

#painel h1{
    font-size: 24px;        
}

#painel h2{
    font-size: 18px;
}
</style>

<div id="painel">

<!-- conta quantos foram chamados, inicializa com 0 -->
<input type="hidden" id="total" value="0"> 

<!-- exibe o nome do proximo -->
<h2>Próximo:</h2>
<h1 id="proximo">Carregando...</h1> 

<hr>
<!-- exibe o nome dos 5 ultimos -->
<h2>Ultimos chamados:</h2>
<div id="ultimos">Carregando...</div> 

<div id="som"></div>

</div>

<!-- jquery -->
<script  src="http://code.jquery.com/jquery-3.3.1.min.js"></script>

  <script>
    setInterval(function(){
        total = $("#total").val();
        $.ajax({
            url: 'painel.php',
            type: 'GET',
            dataType: 'json', //espera o retorno em jSon
            success: function(json){
                //Só chama o proximo se a contagem de pacientes que chegou é maior 
                //que a ultima registrada
                if(total < json.total){
                    //NOME DO ULTIMO
                    $("#proximo").html(json.proximo);

                    $("#proximo").fadeOut(); //efeito para piscar
                    $("#proximo").fadeIn(); //efeito para piscar

                    //ARMAZENA A ULTIMA CONTAGEM
                    $("#total").val(json.total);

                    // escreve os ultimos
                    var nome_ultimos ='';
                    for(i=0; i< json.ultimos.length; i++){
                        nome_ultimos += json.ultimos[i].nome + '<br>';
                    }                    
                    $("#ultimos").html(nome_ultimos);

                    $("#ultimos").fadeOut(); //efeito para piscar
                    $("#ultimos").fadeIn(); //efeito para piscar

                    //REFAZ O HTML DO SOM PRA TOCAR O BEEP
                    $("#som").html("<embed loop='false' src='beep.mp3' hidden='true'  autoplay='true'>");

                }
            }
        });       
    }, 15* 1000); //EXECUTA A CADA 15 SEGUNDOS
  </script>

Explaining this code step by step:

1 - This field is used to store the last n° of name records that arrived from the database. It is not interesting to read the name and compare it with the last because it is common for people to have exactly the same name (For example João Silva).

<!-- conta quantos foram chamados, inicializa com 0 -->
<input type="hidden" id="total" value="0"> 

2 - Place where we will put the name of the last client called:

<!-- exibe o nome do proximo -->
<h2>Próximo:</h2>
<h1 id="proximo">Carregando...</h1> 

3 - Displays the name of the last 5 called (For people to know if they lost the turn or not)

<hr>
<!-- exibe o nome dos 5 ultimos -->
<h2>Ultimos chamados:</h2>
<div id="ultimos">Carregando...</div> 

4 - div that we will use only to reattach the code that plays the sound:

<div id="som"></div>

5 - JQUERY for using ajax:

<script  src="http://code.jquery.com/jquery-3.3.1.min.js"></script>

6 - AJAX request for php panel. - On this page we will :

a) count how many patients we have, to add in the "total" field b) save the name of the next patient c) store an array with the names of the last patients called

(see the code of the.php panel of it at the beginning of the answer)

Explanations in code comments:

<script>
setInterval(function(){
    total = $("#total").val(); //armazena o ultimo total registrado
    $.ajax({
        url: 'painel.php', //url para a qual faremos a requisição e obteremos os dados
        type: 'GET', //metodo GET
        dataType: 'json', //Forma na qual teremos as respostas (JSON)
        success: function(json){ //armazena a resposta na variavel "json"
            //Só chama o próximo se a contagem de pacientes que chegou é maior 
            //que a ultima registrada
            if(total < json.total){

                //NOME DO ULTIMO
                $("#proximo").html(json.proximo);

                $("#proximo").fadeOut(); //efeito para piscar
                $("#proximo").fadeIn(); //efeito para piscar

                //ARMAZENA A ULTIMA CONTAGEM
                $("#total").val(json.total);

                // escreve os ultimos

                var nome_ultimos =''; //inicializa a var

                for(i=0; i< json.ultimos.length; i++){
                    nome_ultimos += json.ultimos[i].nome + '<br>'; // vai concatenando os nomes
                }                    
                $("#ultimos").html(nome_ultimos);

                $("#ultimos").fadeOut(); //efeito para piscar
                $("#ultimos").fadeIn(); //efeito para piscar

                //REFAZ O HTML DO SOM PRA TOCAR O BEEP
                $("#som").html("<embed loop='false' src='beep.mp3' hidden='true'  autoplay='true'>");

            }
        }
    });       
}, 15* 1000); //EXECUTA A CADA 15 SEGUNDOS
</script>
  • on the screen that will be visible to the reception staff, you load the page painel_mostra.php and leave open...

  • Will Knippelberg! It was all I needed. Perfect Coding... Thanks Master!!!

  • Vote as useful answer then to give that moral :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.