Array in php with PDO

1

I need to change my mysqli connection to pdo, and I'm "catching up" when pointing to the index I want to print, look at the example of the model with mysql:

$Busca = mysql_query("SELECT * FROM OrdemServico WHERE Status = '$Status'", $con -> conexaoMysqlP()) or die (mysql_error());
$Consulta = mysql_fetch_array($Busca);
<?php 
do{
<table>
<tr>
<td width="50px"><span class="RAT"><?=$Consulta["RAT"] ?></span></td>
<td width="150px"><?=$Consulta["Clientes"]?></td>
<tr/><table>
}while ($Consulta = mysql_fetch_assoc($Busca));

Now I need it in PDO, but I can not print separate, just all and with the index.

$Pesquisar = $pdo->prepare("SELECT * FROM OrdemServico order by Status");
$Pesquisar -> execute();
$result = $Pesquisar->fetchAll();
<table>
<tr>
<td width="50px"><?=$Consulta["RAT"] ?></td>
<td width="150px"><?=$Consulta["Clientes"]?></td>
<tr/><table>
}while ($result = $Pesquisar->fetchAll());

I hope someone can help me, and thanks for the attention! ^^

    
asked by anonymous 25.09.2016 / 23:11

1 answer

1

You probably need something like this:

<?php

  ...

  $Pesquisar = $pdo->prepare( 'SELECT * FROM OrdemServico order by Status' );
  $Pesquisar->execute();
  $result = $Pesquisar->fetchAll();
  foreach( $result as $Consulta ) {
?>
  <table>
    <tr>
      <td width="50px"><?= $Consulta['RAT'] ?></td>
      <td width="150px"><?= $Consulta['Clientes']?></td>
    <tr/>
  <table>
<?php
  }

The reason is that fetchAll() will already bring all the lines by default, it's no use running more than once. In this case, foreach will serve to iterate one by one.

A more similar way to your original code would be to use fetch instead of fetchAll :

<?php

  ...

  $Pesquisar = $pdo->prepare( 'SELECT * FROM OrdemServico order by Status' );
  $Pesquisar->execute();
  while( $Consulta = $Pesquisar->fetch(PDO::FETCH_ASSOC) ) {
?>
  <table>
    <tr>
      <td width="50px"><?= $Consulta['RAT'] ?></td>
      <td width="150px"><?= $Consulta['Clientes'] ?></td>
    <tr/>
  <table>
<?php
  }
    
25.09.2016 / 23:20