Putting Prepare Inside or Outside the Loop? PDO + PHP

Asked

Viewed 11 times

-1

I use "prepare" PDO for everything, so optimizing my application I saw that I may be doing something "wrong" at the time and I didn’t even think it was the following:

I have a "Database" class that configures the connection, which I don’t think should show, so I’ll show you the part where I’m intrigued

$SQL_VENDAS = "SELECT * FROM VENDAS";

$QueryVendas = Database::Prepare($SQL);
$QueryVendas->Execute();

while ($RowVendas = $QueryVendas->fetch(PDO::FETCH_ASSOC)){

  $PEDIDO = $RowVendas["PEDIDO"];

  $SQL_ITENS = "SELECT * FROM VENDAS_ITENS WHERE PEDIDO = :PEDIDO";

  $QueryItens = Database::Prepare($SQL_ITENS);
  $QueryItens->bindValue(":PEDIDO", $PEDIDO);
  $QueryItens->Execute();

  while($RowItens = $QueryItens->fetch(PDO::FETCH_ASSOC)){
    $CODIGO = $RowItens["CODIGO"];
    $DESCRICAO = $RowItens["DESCRICAO"];
    echo($PEDIDO.": ".$CODIGO." - ".$DESCRICAO."<br>");
  }

}

It works great, but look at the second option with Prepare out of the while:

$SQL_VENDAS = "SELECT * FROM VENDAS";
$QueryVendas = Database::Prepare($SQL);

$QueryVendas->Execute();

if ($QueryVendas->RowCount() > 0){

  $SQL_ITENS = "SELECT * FROM VENDAS_ITENS WHERE PEDIDO = :PEDIDO";
  $QueryItens = Database::Prepare($SQL_ITENS);

  while ($RowVendas = $QueryVendas->fetch(PDO::FETCH_ASSOC)){

    $PEDIDO = $RowVendas["PEDIDO"];
    $QueryItens->bindValue(":PEDIDO", $PEDIDO);
    $QueryItens->Execute();

    while($RowItens = $QueryItens->fetch(PDO::FETCH_ASSOC)){
      $CODIGO = $RowItens["CODIGO"];
      $DESCRICAO = $RowItens["DESCRICAO"];
      echo($PEDIDO.": ".$CODIGO." - ".$DESCRICAO."<br>");
    }

  }

}

I know that the time of Prepare for Queryitens is very fast and could leave as the first example, by the way it is today, but the use "correct" would not be the second option to generate less work to the server?

I’ve been monitoring some Crons that I have and I’ve been receiving notice of excessive use of processing of some scripts and some even freeze, I’ve already scoured all the code, I’ve looked at server logs but I couldn’t find anything that would show where there’s trouble, I ran manually and it’s fast... I did not find problems the scripts work without errors or even warnings, so I decided to analyze my codes to optimize them and I got in this doubt.

No answers

Browser other questions tagged

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