oldboy
oldboy

Reputation: 5964

Possible to reduce complexity of fetching and displaying data?

What I'm doing with the following code is fetching data from a table via PHP in order to display the data on a website.

$stri = "SELECT a, b, c, d, e, f FROM table";
$stat = $conn->prepare($stri);

if ($stat->execute()) {
  while ($resu = $stat->fetch(PDO::FETCH_ASSOC)) {
    foreach ($resu as $key=>$value) {
      echo $value . "<br>";
    }
    echo "<br><br>";
  }
}

However, it seems redundant to use two loops. Is there not a more efficient way to accomplish the same thing while allowing each item of each row to be handled independently?

I plan to do something like the following with it which is why I need to be able to handle the items independently.

if ($stat->execute()) {
  while ($row = $stat->fetch(PDO::FETCH_ASSOC)) {
    echo '<div class="row">';
    foreach ($row as $key=>$value) {
      echo '<div class=' .$key. '>';
      if (empty($value)) echo '---<br>';
      else echo $value;
      echo '</div>';
    }
    echo '</div>';
  }
}

Upvotes: 1

Views: 116

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157916

However, it seems redundant to use two loops.

I cannot get what does it mean, but in all it's quite possible to reduce the complexity. For this you need to use PDO in the full force, not as a just a substitution for mysql_query(). A separation of concerns would also help

Get your data first in the form of array

$sql = "SELECT a, b, c, d, e, f FROM table";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();

and then display it, somewhere inside the HTML part of the page

<?php foreach ($data as $row): ?>
    <div class="row">
    <?php foreach ($row as $key=>$value): ?>
        <div class="<?=$key?>">
        <?php if (!$value): ?>
            ---<br>
        <?php else ?>
            <?=$value?>
        <?php endif ?>
        </div>
    <?php endforeach ?>
    </div>
<?php endforeach ?>

Upvotes: 2

Deno
Deno

Reputation: 434

function checking($val)
{
    if(empty($val))
    {
        echo "---<br>";
    }
    else
    {
        echo $val;
    }
}
$stri = "SELECT a, b, c, d, e, f FROM t";

try
{
    $stat = $conn->prepare($stri);
    $stat->execute();
    $results = $stat->fetchAll(PDO::FETCH_ASSOC);

    foreach ($results as $key=>$value) 
    {
      echo implode('',array_map("checking",$value));
      echo "<br><br>";
    }

}
catch(Exception $e)
{
     error_log($e->getMessage());
}

I do a little bit changed of your code. Instead of use if to catch error, I prefer to use try catch method.

Upvotes: 1

Related Questions