Array in php with PDO

Asked

Viewed 117 times

1

I needed to change my mysqli connection to Pdo, and I am "picking up" at the point of which index I want to print, look at the example of the mysql model:

$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’t print it separately, 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 thank you for your attention!^^

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 the fetchAll() will already bring all lines by default, no use running more than once. In case, the foreach will serve to iterate one by one.

A more similar way to your original code would be to use fetch in place 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
  }
  • Thanks friend, the problem has been solved.... simple thing rsrrs! Again a thank you very much!

Browser other questions tagged

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