Alert message error

Asked

Viewed 1,283 times

0

I would like to know how I can rectify the following problem I am having with the answer from alert. I do the INSERT of items to MySQL, so far so good. However, if some file fails and others can be sent in the loop the warning alert of the error message.

I would like to know how I can change the code below to work as follows:

Count the total value of successfully sent data and data that failed to send, so you can have one alert, example:

Total shipments with HIT X with Flaw X.

<?php
for($i=1; $i<=$total; $i++) {
    // Insere os dados no banco de dados
    $sql = $MySQLiconn->query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'");
}

if($sql) { ?><script>
    alert('<?php echo $total." Itens inseridos com sucesso !!!"; ?>');
    window.location.href='index.php';
    </script><? }
else {
    ?>
    <script>
    alert('error Erro ao tentar inserir os itens tente nova mente');
    </script>
    <?
}
?>
  • 1

    start by fixing the grammar...

  • I didn’t notice anything...

4 answers

1

query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'");
  if ($sql) {
  $total_envios++;
  } else {
  $total_erros++;
  }
}

if ($sql) {
    echo "
        alert('".$total_envios." Itens inseridos com sucesso !!!\n
        ".$total_erros." Itens com falhas no cadastro !!!"."');
        window.location.href='index.php';
        ";
 } else {         
    echo "
        alert('error Erro ao tentar inserir os itens tente nova mente');
        ";
 }

?>
  • 1

    Ola Marcio, welcome to SOPT. Thank you for answering but consider adding a short explanation of what you changed and why you changed.

1


You have to count the query results within the loop:

<?php
    $total_sucesso = 0;
    $total_erros = 0;

    for($i=1; $i<=$total; $i++) {
        // Insere os dados no banco de dados
        if ($MySQLiconn->query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'")) {
            $total_sucesso++;
        }
        else {
            $total_erros++;
        }
    }

    ?><script>
        alert('Total de envios com sucesso <?=$total_sucesso; ?> e erros <?=$total_erros;?>.');
        window.location.href='index.php';
        </script>
    <?
?>  

You can even display a list of the items that were wrong:

    if ($MySQLiconn->query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'")) {
        $total_sucesso++;
    }
    else {
        $total_erros.= $subcat["cat"] . "\n";
    }

And then in the message:

alert('<?=$total_sucesso; ?> envios com sucesso. Erros: <?=$total_erros;?>.');
  • This I had done the method I am currently using creates a list of data sent correctly and fails with everything imagine how the list would look if I send 100 items at once so I chose to use Alert because it is a unique warning.

1

Mixing open PHP tags inside string Javascript is not a good idea, because it makes it difficult to read code.

I suggest simplifying it as follows:

<?php
// salvar os dados em variáveis
$mensagem = 'error Erro ao tentar inserir os itens tente novamente';
$location = false;
if ($sql) {
    $mensagem =  $total . ' Itens inseridos com sucesso';
    $location = 'index.php';
}

// criar e exibir o javascript
echo '<script>';
printf("alert('%s');\n", $mensagem); // <- atenção para as aspas simples
if (!empty($location)) {
    printf("window.location.href = '%s'\n", $location);
}
echo '</script>';

I used the function printf() in a few lines to display the strings formatted. The symbol %s will be replaced by the following parameter. View documentation for more details.

1

The most correct way to do this type of action, is to use Ajax.

  1. PHP does not relate to Javascript and Vice&versa (ñ faça Gambi pfpfpf)
  2. When we need this type of relationship (question - answer) we use the Ajax function

Let’s get down to the problem:

A Query was executed in the Back-End and after was informed the result. As javascript can not see this answer, so far we do not have a solution.

To arrive at a solution, you will need to make use of Ajax, which will trigger a request to your file, and in this request, you will say that you need a response, using HTTP semantics that in case will be GET.

The answer will come in the body of your request, and in javascript you will then receive this response, and you can evaluate the result. So you can send a message to the user.

Practical example using Jquery

$.get('/pagina_do_meu_site&ajax="verifica"').success(function(response){
    if(response>0){
      alert('Itens inseridos com sucesso');
    }else{
      alert('Houve falha na inserção de dados');
    }
});

In PHP back-end (I will use the simplest mode)

<?php
  if($_GET['ajax']=='verifica'){
      echo '1';  //aqui o php retornará o valor 1 para o javascript
      exit;
  }
?>
  • Without Not Enough jQuery, please. Using ajax is Overkill for such a simple thing! Javascript is being used ONLY to display a message, nothing else! Do you want to use ajax for this? The way it is being made perfectly meets what the OP wants. Imagine if the user makes 10 inserts at the base, it’s 10 piping Alerts on his screen... ridiculous.

  • Young man, using the easiest way is not always the right way. That’s why PHP programmers are poorly seen within companies, for taking that kind of attitude.

  • I didn’t say easier, said more coherent. You do not know how the information is being sent, how is the form or anything, and already come suggesting all this ? Total change of structure ?

  • Only php allows face, so it is so poorly seen, it does not exist, communicate directly back-end with front-end.

  • I know, but this is a broader context. You don’t know how the user’s structure is, nor if it separates the layers. Anyway...

  • That’s not why my answer is wrong. There’s a difference between you getting a default user and a default user. No wonder I despise such answers. My answer was to show the difference between design patterns, if you have negatively affected me, fine, it’s your right. There are two parallel worlds young, I’m showing one side.

  • Exactly, I didn’t say the answer is wrong or bad, it’s just not pertinent to the question. You can suggest as a comment the change of structure, but not as a response, in my opinion. And still with technologies (ajax and jquery) that were not even related in the question. In the gringo you would have received some 10 negative votes.

  • 1

    ^^ Ta serto (y)

  • Grateful for all your help.

Show 4 more comments

Browser other questions tagged

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