PHP function only works on the first call

Asked

Viewed 81 times

0

I am calling the same php function, in which I pass as parameter a database result, twice in the script but it only works in the first call.

I realized that if I call the function that returns the query result and pass to another variable that in turn is passed as parameter to the function that previously did not work, it goes to work.

I know I’m missing some point of php working, I’d like a hand in this.

Remembering that I am calling the same function because I need a select exactly like the previous one, does anyone suggest any more optimized way to do this? Because the function carries approximately 13,000 bank records which makes the page take a long time to load.

<!--TIMES-->
<div class="page-header">
    <h4>Times</h4>
        <hr>
</div>
<?php
    $registro = lista_times();
    //$registro2 = lista_times();
?>
<div style="padding: 20px; align-content: center" class="row" id="times-row">
    <div class="col-sm-6">
        <div class="form-group">
            <label for="time_casa" class="col-sm-2 control-label">Casa</label>
            <div class="col-sm-10">
                <?php //var_dump($registro); ?>
                <select style="width: 300px" class="form-control chosen-select" id="time_casa" name="time_casa" data-error="Por favor, selecione o time de casa." required>
                    <?php echo preenche_time_combo($registro); ?>
                </select>
            <div class="help-block with-errors"></div>
        </div>
    </div>
</div>

<div class="col-sm-6">
    <div class="form-group">
        <?php //var_dump($registro); ?>
        <label for="time_fora" class="col-sm-2 control-label">Fora</label>
        <div class="col-sm-10">
            <select style="width: 300px" class="form-control chosen-select" id="time_fora" name="time_fora" data-error="Por favor, selecione o time de fora." required>
                <?php echo preenche_time_combo($registro); ?>
            </select>
        <div class="help-block with-errors"></div>
    </div>
</div>
</div>
</div>
<!--TIMES-->

lista_times() executes the query and returns the result and preenche_time_combo() returns a string with html code with an option for each element recovered from the database.

//Lista todos os jogos ativos
function lista_times()
{
    $link = conectar();
    $query = "SELECT tb_time.id as id_time, tb_time.nome_time, tb_campeonato.nome_camp
              FROM tb_campeonato, tb_time
              WHERE tb_time.tb_campeonato_id = tb_campeonato.id";
    $result = mysqli_query($link, $query) or die(print_r(mysqli_error()));

    return $result;

}

function preenche_time_combo($result)
{
    $header_atual="";

    $html="";

    while ($registro = mysqli_fetch_assoc($result)) {
        if($registro['nome_camp'] != $header_atual){
            if($header_atual != ""){
                $html .= "</optgroup>";
            }

            $html .= "<optgroup label='".$registro['nome_camp']."'>";
            $header_atual = $registro['nome_camp'];
        }

        $html .= "<option value='" . $registro['id_time'] . "'>" . $registro['nome_time'] . "</option>";
    }

    $html .= "</optgroup>";

    return $html;

    exit();
}
  • 1

    Amigo 2 combos with 13 thousand records will claw, you ever tried using an ajax to mount an autocomplete? Want some plugin suggestions?

  • @Euler01, I would love some suggestions. I did some research on how to optimize this but could not find a satisfactory solution. Thank you if your friend can help me, hug!

  • The mysqli_fetch_assoc, according to the documentation, "returns an associative matrix that corresponds to the obtained line and moves the internal pointer of the data forward." That is, you would need to restart the pointer to the first record to go through the result again (with mysqli_data_seek). I’m not sure it’s a good alternative.

  • Are you really going to go through with the 13,000 records on one page? http://answall.com/questions/146765/optimizar-chargingde-select-phpmysql Now in addition to 13 mì there are 26,000.. and all within select option...

  • Hello @Guilhermeramalho, take a look at https://select2.github.io and look for "Loading remote data". You’ll need to import Bootstrap css as well. Or good old http://jqueryui.com/autocomplete/

1 answer

3


In preenche_time_combo() every call from mysqli_fetch_assoc($result) is altering/emptying the variable $registro out of function (change by reference), so the second call does not work.

The simplest way to solve this is to store the options already generated in a variable and then print it inside the <select>

Change the call:

<?php
   $registro = lista_times();

To:

<?php
   $options = preenche_time_combo(lista_times());

And finally (I removed the style to simplify the example):

<select>
   <?php echo $options;?>
</select>
  • It worked right! Thanks for the tip, man! Now I just need to find a way to optimize the load. What do you think of the performance? I’m going to leave a video for you to look at. It’s going to get a lot worse when it’s hosted on a server and there’s traffic, right? https://www.youtube.com/watch?v=uoB7-U7askQ

  • @Guilhermeramalho pq vcprecisa carregar tanto registros do banco? se resolveu pode marcar a resposta como aceita como sinal verde, veja em How and why to accept an answer?

  • These records are the list of every football team in the world. The user should be able to choose two teams from one match between any team in the world. I thought to limit the consultation to the teams belonging to the championship "x" selected in the first select but there are cases where I can not limit to the championship.

  • @Guilhermeramalho and separate by country would not be better?

  • I also thought but some records that are in the table tb_pais are not actually countries, but can be treated as such. I didn’t really know how much of a resource the load of these records would consume given that this is my first web system and that at first glance, as in the video, it didn’t take long to load. But I appreciate all the tips. Just one question: jquery would take the database records and make an HTML append, right? Out that the page would load first and the records later would have gained performance beyond the aesthetics of the page that would not show the elements more?

Browser other questions tagged

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