0

Is is possible to loop two times through a result from a pdo query ? the first function is to get the query results

function querySelectBrand($pdo)
{
    $table01 = 'brand';
    $table02 = 'text';  
    $querySelectBrand="SELECT $table01.*,
                    textDef.$table02 as defText,
                    textUsr.$table02 as usrText
                    FROM $table01
                    LEFT JOIN $table02 as textDef on $table01.textId = textDef.textId And textDef.languageId = $_SESSION[defaultLanguage]
                    LEFT JOIN $table02 as textUsr on $table01.textId = textUsr.textId And textUsr.languageId = $_SESSION[defaultLanguage];";
//  echo $querySelectBrand;
    $stmt = $pdo->prepare($querySelectBrand);
    $stmt->execute([]);
return $stmt;
}

then I pass the $stmt as $result to a function to build a drop down box.

function dropDownBox($result, $name, $size, $selected)
{
$x=1;
echo'<select name="'.$name.'" size="'.$size.'">';
foreach($result AS $row01){
    $id=$row01['id'];
    if(isset($row01['usrText'])){$text=$row01['usrText']; }else{$text=$row01['defText']; }
    if(isset($selected)and $id==$selected){
        echo '<option value="'.$id.'" selected>';
        echo $text;
        echo '</option>';
    }else{
        echo '<option value="'.$id.'">';
        echo $text;
        echo '</option>';
    }
}
echo'</select>';
reset($result);
foreach($result AS $row01){
    $x++;
}
?>
    <input type="text" name="testresult" value="<?php echo $x; ?>">
<?php
}

How can I make the second foreach loop go through the $result again ? the output from $x is now 1.

reset($result);

does not work.

anatak
  • 440
  • 2
  • 7
  • 16
  • Is it just me or are you trying to loop though the result just to count how many rows it has? If so why don't you count while in the first loop? At any rate PDO doesn't do this because not all databases support treating results as iterators. – apokryfos Dec 07 '17 at 07:20
  • You might need to cache the results yourself as php doesn't seem to cache the results. This might be due to query reuse feature of pdo. – Cholthi Paul Ttiopic Dec 07 '17 at 07:24
  • the real reason I want to loop 2 times is because I want to build an array of fields so that I can pass the $id and the $text to the page that will process this form. – anatak Dec 07 '17 at 07:30
  • How can I cache $result ? – anatak Dec 07 '17 at 07:33

0 Answers0