2
\$\begingroup\$
<script>
<?php
unset($data0);
unset($data1);
unset($data2);

$sth = $dbh->prepare("
SELECT a, b, c
FROM   t
");
$sth->execute();
?>

Morris.Line({
  element: 'morris-line-chart',
  data: [
  <?php
  while ($row = $sth->fetch()) { ?>
    { m: '<?php echo $row['0']; ?>', a: <?php echo $row['1']; ?>, b: <?php echo $row['2']; ?> },
  <?php } ?>
  ],
  xkey: 'm',
  xLabels: 'month',
  ykeys: ['a', 'b'],
  labels: ['2014', '2015']
});
</script>

Is there a cleaner way to write it, especially the PHP echoing to create the JavaScript?

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

I like to keep the Javascript in one echo at the bottom, like this:

<?php

unset($data0);
unset($data1);
unset($data2);

$sth = $dbh->prepare("SELECT a, b, c FROM t");
$sth->execute();

$data = '';
while ($row = $sth->fetch(FETCH_ASSOC)) { 
  extract($row);
  $data .= "{ m: '$c', a: $a, b: $b },".PHP_EOL;
} 

echo "<script>
Morris.Line({
  element: 'morris-line-chart',
  data: [$data],
  xkey: 'm',
  xLabels: 'month',
  ykeys: ['a', 'b'],
  labels: ['2014', '2015']
});
</script>";

I had to make the assumptions that you're using PDO and that $c is your m in the morris line.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.