Progress bar track mysql query execution

Asked

Viewed 5,346 times

3

I need a bootstrap bar to track 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, it generated me 200 progress bars, each with a value up to 100%

I need you to generate only 1 (one) bar and progress is updated up to 100% with each run.

Note. 1: I imagine that only php does not solve and that it is necessary JS and CSS;

Note. 2: Code has been reduced to question-focused understanding;

Note. 3: Yes, I need to update to mysqli :)

Thanks in advance.

  • 1

    I don’t think that’s possible. From the moment you pass the command to the bank you have no more control, you just sit back and wait until the timeout wins. You’ve seen it working somewhere?

  • Imagine it working. You would pass along with the command the select a callback function and it - the bank - the measure that selects warns via callback how much more to finish. No. Definitely not likely.

  • It is possible to divide the queries and count how many more to go, passing this data with JQuery pro parameter of progressbar of bootstrap.

  • I initially thought about updating the bar div to each query run... via ajax or something. But I really don’t know how to run it. I don’t have much skill with JS...

  • Hello, What you want is while progressibar and not select. Right?

  • This, do while. This would return an evolution of 200 movements until it reached 100%, correct?

  • see if help -> http://answall.com/questions/107151/como-usar-progressbar-com-ajax-e-php/107895

Show 2 more comments

1 answer

4


Instead of the progress bar, I’ll suggest what I did. It’s simpler, and it doesn’t demand multiple requests from the server. Basically: show a modal with a warning during the execution time of the consultation.

May be a modal, may be a div, or a alert, etc..

I faked it with a query which inserts 1200 records into a table taking on average about 3 seconds. During these 3 seconds the user sees this:

inserir a descrição da imagem aqui

When the script testing.resp.php responds, the user sees this:

inserir a descrição da imagem aqui

If the answer comes with failure, the user sees this:

inserir a descrição da imagem aqui

Follow the codes:

testing.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-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';
  • I imagined that there would be a little complex method, with ajax for example, since, in the proposed case, we have a defined universe of 200 and no need to check buffer, load time etc. Just "add 1" to a variable in each query execution (without updating the page).

  • To avoid a locking problem, you can still define a timeout, that is a time limit for the response. If the response takes longer than the given time, you interrupt and send a warning to the user. Almost anything is possible :)

Browser other questions tagged

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