Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
<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?

share|improve this question

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.