The less consultation the better, right?

Asked

Viewed 174 times

4

It is possible to vary the writing of the results, as an example below where I want to use.

<table width="1000" align="center">
    <tr> 
      <td>&nbsp;NOTICIAS</td>
      <td>&nbsp;</td>
    <tr> 
      <td width="350"> <?php
                                $sql = "SELECT * FROM noticias WHERE categoria='noticias' ORDER BY idnoticia DESC LIMIT 1";
                                $stmt = DB::prepare($sql);
                                $stmt->execute();
                                $exibe = $stmt->fetchAll();
                                foreach ($exibe as $u) { 
                                echo "<div style='float:left;width:99%;margin-right:10px;'><a  style='color:#000;text-decoration:none;' href='{$u->categoria}.php?idnoticia={$u->idnoticia}'>";
                                echo "<div class='thumbnail'> <img src='img/{$u->idnoticia}/{$u->imagem}' class='img-responsive'>";
                                echo "<div class='limit'>{$u->titulo}";
                                echo "</div></div></a></div>";

                                ?></td>
      <td width="650"><?php
                                $sql = "SELECT * FROM noticias WHERE categoria='noticias' ORDER BY idnoticia DESC LIMIT 6 OFFSET 1";
                                $stmt = DB::prepare($sql);
                                $stmt->execute();
                                $exibe = $stmt->fetchAll();
                                foreach ($exibe as $u) { 
                                echo "<div style='float:left;width:99%;margin-right:10px;'><a  style='color:#000;text-decoration:none;' href='{$u->categoria}.php?idnoticia={$u->idnoticia}'>";
                                echo "<div class='thumbnail'> <img src='img/{$u->idnoticia}/{$u->imagem}' class='img-responsive'>";
                                echo "<div class='limit'>{$u->titulo}";
                                echo "</div></div></a></div>";

                                ?></td>
  </table>

I can enjoy the same select used in the first <td> to continue the result after 2° <td>? How to write the first result, "pause" and rewrite the rest in another way?

  • 1

    Look, I can’t tell you if this is real, but as far as I know, it’s not a single user access that’s gonna make a difference, but when we’re on a server and multiple users access at the same time, there could be an increase in server machine usage, which is, by the logic I’m proposing here, the more connections, the less "performance", the less "better" connections, correct me if I’m wrong.

  • Because then, I also do not believe that it is the access of a single user that will make the difference, but I think exactly in this case of many accesses Imultaneos, up to how much can be harmful 2 queries, and in the case could be ( I think ) that used only one?

  • In my view then the question would be to create a page cache structure when possible (besides doing a query only) and in a matter of optimizing php, you could use fetch instead of fetchAll and not use buffers in queries, example with Pdo $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

2 answers

7


Yes, it is possible. I am considering that the code is correct (but I think it has errors):

<?php
$sql = "SELECT * FROM noticias WHERE categoria='noticias' ORDER BY idnoticia DESC LIMIT 6";
$stmt = DB::prepare($sql);
$stmt->execute();
$exibe = $stmt->fetchAll();
?>
<table width="1000" align="center">
    <tr> 
      <td>&nbsp;NOTICIAS</td>
      <td>&nbsp;</td>
    </tr>
    <tr> 
      <td width="350">
          <?php
          echo "<div style='float:left;width:99%;margin-right:10px;'><a  style='color:#000;text-decoration:none;' href='{$exibe[0]->categoria}.php?idnoticia={$exibe[0]->idnoticia}'>";
          echo "<div class='thumbnail'> <img src='img/{$exibe[0]->idnoticia}/{$exibe[0]->imagem}' class='img-responsive'>";
          echo "<div class='limit'>{$exibe[0]->titulo}";
          echo "</div></div></a></div>";
          ?>
      </td>
      <td width="650">
          <?php
          $tamanho = count($exibe);
          for ($i = 1; $i < $tamanho; $i++) { 
              echo "<div style='float:left;width:99%;margin-right:10px;'><a  style='color:#000;text-decoration:none;' href='{$exibe[$i]->categoria}.php?idnoticia={$exibe[$i]->idnoticia}'>";
              echo "<div class='thumbnail'> <img src='img/{$exibe[$i]->idnoticia}/{$exibe[$i]->imagem}' class='img-responsive'>";
              echo "<div class='limit'>{$exibe[$i]->titulo}";
              echo "</div></div></a></div>";
          }
          ?>
        </td>
    </tr>
</table>

I put in the Github for future reference.

You read all 6 items you want at once, then use the first one separate from the next 5. Instead of two trips to search for the information in the database, you do only one and resolve the separation within PHP.

  • it was really that the intention, I will test here, I believe that making only 1 query the response of the site should get faster

  • 1

    In fact, your original question is on the right track, should always save travel to the database.

  • 2

    @Arsomnolasco you have 27 questions and only 8 votes given. Do you know that you can vote too? And that this is important? Can you even vote on other things on the site? http://meta.pt.stackoverflow.com/q/159/101 Even has a ranking of who votes more http://answall.com/users?tab=Voters&filter=all See [tour] It would be nice to review the questions you have asked if you have answers that deserve your vote. Or even see if you have questions on the site that deserve your vote, plus answers on them that helped you learn something new or can help other people.

  • I did it the way you suggested and it’s okay but there’s something that generates the most see attached image http://prntscr.com/6piust will be something in Count?

  • I can’t figure out exactly what’s different. The biggest news is the first one listed and the others are the rest? You’re showing 1 + 8, did you change it? There would be a 10a. news that shouldn’t be shown but shouldn’t be? Is that the problem? If so, you have already changed the original code, I do not know if this modification has been made correctly. If it’s not this, your code seems to do something very different from what is being shown. It’s not easy to say something without seeing the actual code.

  • yes 1+8 , in case the 10th was not to be shown, it seems to be counted 1 more see the print of my modified code http://prntscr.com/6pj1j2

  • I ate ball, the comparison operator is wrong even, it was to use, < and not <=.

  • It really was that, <= he tells the first one too, I didn’t even notice. now this bunito, then I signal my vows to Daki 5 hours again, followed his advice and reviewed my questions was the least

Show 3 more comments

5

Each case is a case, but in your case, yes, the fewer queries the better! Also because you’re essentially repeating the same query.

Usually in PHP, the tendency is to divide the information handling into 3 different layers, in order to facilitate reading and future maintenance. In your case, we’re essentially talking about:

  1. Data layer - Interaction with database
  2. Business layer - Processing of information
  3. Layer interface - THE HTML

Applying this concept, we are already answering your question because if we are going to treat the information before using it, a query serves to bring all the "news" and in the treatment phase we separate the first from the others:

  1. Interact with database

    /* Data layer
     * Consultar base de dados para recolher informação
     */
    $sql = "SELECT * FROM noticias WHERE categoria='noticias' ORDER BY idnoticia DESC LIMIT 7";
    $stmt = DB::prepare($sql);
    $stmt->execute();
    $exibe = $stmt->fetchAll();    
    
  2. Work and prepare information

    /* Business layer
     * Trabalhar os dados preparando o HTML a inserir na interface
     */
    $primeiraNoticia = $outrasNoticias = '';
    $contador = 0;
    
    foreach ($exibe as $u) {
    
        $noticia = '
        <div class="noticiasWrapper">
          <a href="'.$u->categoria.'.php?idnoticia='.$u->idnoticia.'">
            <div class="thumbnail">
              <img src="img/'.$u->idnoticia.'/'.$u->imagem.'" class="img-responsive">
              <div class="limit">'.$u->titulo.'</div>
            </div>
          </a>
        </div>';
    
        if ($contador>0) {
          $outrasNoticias .= $noticia;
        } else {
          $primeiraNoticia .= $noticia;
        }
    
        $contador++;
    }
    
  3. Present the information

    <!-- Interface layer
         Aplicar a informação no nosso layout e enviar a mesma para o navegador
     -->
    <style type="text/css">
        /* CSS deve ficar em ficheiro .CSS mas caso no documento,
           desta forma não andamos a duplicar a informação para o navegador */
        .noticiaWrapper{
          float:left;width:99%;margin-right:10px;
        }
        .noticiaWrapper > a{
          color:#000;text-decoration:none;
        }
    </style>
    
    <table width="1000" align="center">
        <tr>
            <td>NOTICIAS</td>
            <td> </td>
        </tr>
        <tr>
            <td width="350"><?php echo $primeiraNoticia; ?></td>
            <td width="650"><?php echo $outrasNoticias; ?></td>
        </tr>
    </table>
    

Notes: You can have everything in the same file .PHP in the order shown above, or later come to split into multiple files in an agile way since you already have the different layers properly separated.

Browser other questions tagged

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