Question

I have the following PHP code:

echo "var s1 = [";
$count = 0;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
  {
  if ($count++ > 0) echo ", ";
  echo $row['OrdersBal'];
  }
echo "];\n";
echo "var ticks = [";
$count2 = 0;
while($row2 = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
  {
  if ($count2++ > 0) echo ", ";
  echo "'" . $row2['CardName'] . "'";
  }         
echo "];\n";

It's currently outputting:

var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = [];

But I want it to output:

var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = ['Parameter Technology', 'Earthshaker Corporation', 'Microchips', 'Mashina Corporation', 'SG Electronics'];

If I move the second while statement so that it occurs first then that statement will output correctly. This has lead me to believe that I can't execute two while statements in a row in this fashion, but I'm not sure what my alternatives are. Thanks for any help!

Was it helpful?

Solution

Use variables to store text during loop and then print them out:

$count = 0;
$orders = "";
$cardNames = "";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
    if ($count++ > 0)
    {
        $orders .= ", ";
        $cardNames .= ", ";
    }
    $orders .= $row['OrdersBal'];
    $cardNames .= $row['CardName'];
}

echo "var s1 = [" . $orders . "];\n";
echo "var ticks = [" . $cardNames . "];\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top