0

I am trying to print out all rows and columns in a test table I have created.

My relevant code:

    $sql = "select * from ITEM";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

//    $stmt->execute(array(
//    $_POST['ModuleID']
//      ));
//     $result = $stmt->fetch();
     $result = $stmt->fetchAll();
     foreach ($result as $row)
     {
       echo "<TR>";
//       echo $row[0];
     foreach ($row as $col) {
//       for ($i = 0; $i < 5; $i++) {
         echo "<TD>";
//         echo $row[$i];
         echo $col;
         echo "</TD>";
       }
       echo "</TR>";
     }

So my issue is that when I try to iterate manually on the row values (you can see where I tried where I have for($i =0; $i < 5; $i++)) I don't know how to get the number of columns, so it is only printing out 5. When I switched to using foreach($row as $col) I can see all data, but for each column a duplicate is generated right after.

So I am seeking either a way to find the length of columns in the result set programmatically, or to find a way to use my foreach solution where it only generates 1 column

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • can you post the table and the result? – Vidal Feb 22 '19 at 18:55
  • What do you mean by "length of columns"? – tshimkus Feb 22 '19 at 18:56
  • 1
    Can you post `print_r($result)`? It sounds like the `PDO::ATTR_DEFAULT_FETCH_MODE` might be `PDO::FETCH_BOTH`. Usually it's most useful to set this to `PDO::FETCH_ASSOC` (see my post above) but there are various options—see [PDO Predefined Constants](http://php.net/manual/en/pdo.constants.php) for more info. – Darragh Enright Feb 22 '19 at 18:59

1 Answers1

1

Because PDO is returning an array like this:

[0] => Array
        (
            [name] => apple
            [0] => apple
            [colour] => red
            [1] => red
        )

And when you loop all the rows, you have the result by index and associative.

http://php.net/manual/en/pdostatement.fetchall.php

Try $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

Vidal
  • 2,605
  • 2
  • 16
  • 32