Error handling in consultation

4

How can I make error handling in this scenario and if there are errors, for example in connection or declaration, display them on the screen?

returnClient.php

<?php 

        $hostname="localhost";  
        $username="USUARIO";  
        $password="SENHA";  
        $db = "Nome_DB";  
        $pdo = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);

    $assunto = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_STRING);


    $buscar = $pdo->prepare('SELECT NOME_LOJA FROM lojas WHERE NOME_LOJA LIKE ? ORDER BY NOME_LOJA ASC');
    $buscar->execute(array("%$assunto%"));

    while ($results = $buscar->fetch())
    {
        $data[] = $results['NOME_LOJA'];
    }


    //SQL para selecionar os registros
    $result_msg_cont = $pdo->prepare('SELECT assunto FROM mensagens_contatos WHERE assunto LIKE ? ORDER BY assunto ASC LIMIT 7');
    $result_msg_cont->execute(array("%$assunto%"));

    while ($row_msg_cont = $result_msg_cont->fetch())
    {
        $data[] = $row_msg_cont['assunto'];
    }


    echo json_encode($data);

?>

HTML

  ............
  .............
  <input type="text" id="assunto" name="assunto">
  </form>

    <script type="text/javascript">
        $(document).ready(function(){
            $("#assunto").autocomplete({
                source: 'retornaCliente.php' 
            });
        });

    </script>
    ...............
    ...............
  

The treatment I used

    try{
        $pdo = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
    }catch(PDOException $e){
        exit("Erro na conexão com a base de dados");

    }
  

but the difficulty is to show some message on the screen

    
asked by anonymous 13.09.2018 / 15:44

1 answer

4
  

The answer to this question is in the fiddle of @Sam indicated in his comment and in the @Bacco SOen. But as these links may not exist in the future, I'll put the solution here.

javascript

$(document).ready(function(){
    $( "#assunto" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            $.ajax({
                url: "retornaCliente.php",
                data: { query: request.term},
                success: function(data){
                    response(data);
                },
                error: function(jqXHR, textStatus, errorThrown){
                  //  coloque aqui a mensagem que quiser
                  //$("...").modal('show'); 
                  //alert (...); 
                  //exibir numa div                   
                },
              dataType: 'json'
            });
        }
    });   
});

PHP

$assunto = filter_input(INPUT_GET, 'query', FILTER_SANITIZE_STRING);
    
14.09.2018 / 06:12