Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

312
Visualizações
Is there a way to count how many database results the PHP sends back to jQuery?

In my project, I use PHP to query the database(in my case, SELECT) and use while loop to fetch each row, and use it to echo back to ajax.

Like in my PHP:

$sql = "SELECT * FROM tasks A WHERE A.open = '1'";

$stmt = $pdo->prepare($sql);

$stmt->execute();

while ($row = $stmt->fetch()){
    echo $row["orderDetails"];
}

In my HTML:

<script>
    $(function(){
        $.ajax({
            method: "POST",
            url: "getDetails.php",
            success: function(backData){
                $("#details").html(backData);
            }
     });
<script>

Let's say I query the database for the open tasks in my task table where task.open=1, then inside of each open task, I echo back to my ajax about these tasks details, and my ajax will change the html of the div about the task details.

So basically, the number of the open tasks, aka the number of the while loops, is the number of the echos. What is the best way to grab this number so I can show in the html how many tasks are listed here?

PS: I tried to catch this number by adding a while loop counter inside of the while loop, and add this number to an attribute of the div and echo back to ajax, however, I don't know why this echo will not take place in my end.

Thanks guys!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I solved it by adding a div with a class attribute to the echo to contain this order details and then back to my html I used jQuery to count the div with that specific class and get the number. I get the hint from here: count div elements with the same id JQUERY But you are very welcome to post a better solution for this :D

over 4 years ago · Santiago Trujillo Relatório

0

What you want to do is send back a proper JSON response, then you can just use the length property to check how many items there are. You don't need a loop to do this, just use PDO's fetchAll method. Since you are only selecting a single column, you can get it as an array of strings.

<?php
$sql = "SELECT orderDetails FROM tasks WHERE open=1";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
header("Content-Type: application/json");
echo json_encode($array);

Now you have an array of strings, you can do what you want with it, including getting its length.

<script>
$(function(){
    $.ajax({
        method: "POST",
        url: "getDetails.php",
        success: function(backData) {
            // now you can work with backData as an object
            var count = backData.length;
            $("#details").append("<div>You have " + count + " results.</div>");
            for (var i = 0; i < count; i++) {
                $("#details").append("<div>" + backData[i] + "</div>"
            }
        }
    });
});
<script>

Also note you were missing a closing }) pair in your JavaScript code.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda