Search code examples
phppdoiterationresultset

Why am I getting my column values in my result set twice?


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


Solution

  • 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);