Progress bar follow execution of mysql query

3

I need a bootstrap progress bar to follow the execution of a mysql query.

$limite='200'; // limita
$i=1; // para gerar o looping da barra de progresso

$y = mysql_query("SELECT * FROM $tabela WHERE x='y' ORDER BY rand() limit $limite");
while($x = mysql_fetch_array($y)){

// gera a barra de progresso
$a_valor = $i / $limite * 100;
if($a_valor<'30'){$a_cor='danger';}elseif($a_valor>='30' && $a_valor<='70'){$a_cor='warning';}else{$a_cor='success';}
echo'
<div class="progress">
<div class="progress-bar progress-bar-'.$a_cor.'" role="progressbar" aria-valuenow="'.$a_valor.'" aria-valuemin="0" aria-valuemax="100" style="width:'.$a_valor.'%">
'.$a_valor.'% Completo
</div>
</div>';
$i++;
// gera a barra de progresso

}

As I expected, this generated me 200 progress bars, each with a value of up to 100%

I need to only manage 1 (one) bar and the progress is updated up to 100% with each execution.

Obs. 1: I imagine that only php does not resolve and that it takes JS and CSS;

Obs. 2: The code has been reduced to understanding focused on the question;

Obs. 3: Yes, I need to upgrade to mysqli:)

Thank you in advance.

    
asked by anonymous 29.12.2016 / 15:11

1 answer

2

Instead of the progress bar, I'll suggest what I did. It is simpler, and does not require multiple requests to the server. Basically: show a modal with a warning during the query execution time .

It can be a modal , it can be a div , or a alert , etc.

I simulated with a query that inserts 1200 records into a table, taking, on average, about 3 seconds. During these 3 seconds the user sees this:

Whentestingtesting.resp.phpresponds,theuserseesthis:

Iftheresponsecomescrashing,theuserseesthis:

Herearethecodes:

testing.php

<!DOCTYPEhtml><html><head><metahttp-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js"integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <style>
            /*Regra para a animacao*/
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            /*Mudando o tamanho do icone de resposta*/
            div.glyphicon {
                color:#6B8E23;
                font-size: 38px;
            }
            /*Classe que mostra a animacao 'spin'*/
            .loader {
              border: 16px solid #f3f3f3;
              border-radius: 50%;
              border-top: 16px solid #3498db;
              width: 80px;
              height: 80px;
              -webkit-animation: spin 2s linear infinite;
              animation: spin 2s linear infinite;
            }
        </style>
        <script>
            $(function () {
                //Comportamento do botao de disparo
                $('#btn-getResponse').click(function () {
                    getResponse();
                });
            });
            /**
             * Dispara o modal e espera a resposta do script 'testing.resp.php'
             * @returns {void}
             */
            function getResponse() {
                //Preenche e mostra o modal
                $('#loadingModal_content').html('Carregando...');
                $('#loadingModal').modal('show');
                //Envia a requisicao e espera a resposta
                $.post("testing.resp.php")
                    .done(function () {
                        //Se nao houver falha na resposta, preenche o modal
                        $('#loader').removeClass('loader');
                        $('#loader').addClass('glyphicon glyphicon-ok');
                        $('#loadingModal_label').html('Sucesso!');
                        $('#loadingModal_content').html('<br>Query executada com sucesso!');
                        resetModal();
                    })
                    .fail(function () {
                        //Se houver falha na resposta, mostra o alert
                        $('#loader').removeClass('loader');
                        $('#loader').addClass('glyphicon glyphicon-remove');
                        $('#loadingModal_label').html('Falha!');
                        $('#loadingModal_content').html('<br>Query nao executada!');
                        resetModal();
                    });
            }
            function resetModal(){
                //Aguarda 2 segundos ata restaurar e fechar o modal
                setTimeout(function() {
                    $('#loader').removeClass();
                    $('#loader').addClass('loader');
                    $('#loadingModal_label').html('<span class="glyphicon glyphicon-refresh"></span>Aguarde...');
                    $('#loadingModal').modal('hide');
                }, 2000);
            }
        </script>
    </head>
    <body>
        <!-- loadingModal-->
        <div class="modal fade" data-backdrop="static" id="loadingModal" tabindex="-1" role="dialog" aria-labelledby="loadingModal_label">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="loadingModal_label">
                            <span class="glyphicon glyphicon-refresh"></span>
                            Aguarde...
                        </h5>
                    </div>
                    <div class="modal-body">
                        <div class='alert' role='alert'>
                            <center>
                                <div class="loader" id="loader"></div><br>
                                <h4><b id="loadingModal_content"></b></h4>
                            </center>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- loadingModal-->
        <nav class="navbar"></nav>
        <div class="container">
            <button type="button" class="btn btn-default" id="btn-getResponse">
                getResponse
            </button>
        </div>
    </body>
</html>

testing.resp.php

<?php

# descomentar para testar resposta com falha
//header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); exit();

$servername = "localhost";
$username = "root";
$password = "#Senha";
$dbname = "#NomeBanco";

$mysqli = new mysqli($servername, $username, $password, $dbname);

if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}

$sql = "TRUNCATE teste;";

for ($i = 1; $i <= 1200; $i++) {
    $sql .= "INSERT INTO 'teste' ('title','slug','text') VALUES ('".md5($i)."','".sha1($i)."','text$i');";
}

if (mysqli_multi_query($mysqli, $sql)) {
    do {
        if ($result = mysqli_store_result($mysqli)) {
            header($_SERVER['SERVER_PROTOCOL'], true, 200);
            exit();
        }
    } while (mysqli_next_result($mysqli) && mysqli_more_results($mysqli));
}
mysqli_close($mysqli);

table

--
-- Estrutura para tabela 'teste'
--

CREATE TABLE IF NOT EXISTS 'teste' (
'Id' int(11) NOT NULL,
  'title' varchar(255) DEFAULT NULL,
  'slug' varchar(255) NOT NULL,
  'text' text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8 COMMENT='Teste';
    
15.01.2017 / 23:23