0

I am doing this little project. Everything seems working , but I want to make even better. I have code

-Part1 -takes date from database and converts to JSON

<?php
$sth = mysql_query("select Value, Stats from table");
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Stats']); 
$temp[] = array('v' => (int) $r['Value']); 
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
?>  

-Part 2 Draws Google Bar chart and shows it on page

<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);   
   var options = {
    legend: {position: 'none'},
           bar: {groupWidth: "85%"},
           colors:['#4A9218'],
    hAxis: {viewWindowMode: 'explicit'},
  }                        };                  
  var chart = new google.visualization.BarChart(document.getElementById('charts_div'));
  chart.draw(data, options);
}
</script>
<div class='data' id="charts_div" style="width:100%; height:200px"></div>

-My Qyestion

How to convert (combine) Part2 code to php. I tried echo around lines, but unsuccesfully

I want to assign Part2 as Php variable $Graph1 and then echo $graph1 on page, because It works better with my other code, so its consistent.

So I would like something like:

<?php
Part1
?>
<?php
$graph1=."<script>...</script>"
$graph = "<div class='data'><ul>" . $graph1 . "</ul></div>
echo $graph
?> 
1
  • Here's a clean way to deliver data to the client runnable Commented Feb 5, 2014 at 17:40

1 Answer 1

1

Why don't you just add it after the ?> ?

In PHP you can include HTML like this

<?php
// My PHP Code
echo "test";
?>
<H1>My Title in HTML</H1>
<script> ... </script>
<?php
echo "test2";
?>

You can also include PHP into HTML

<script> var a = "<?php echo $somevariable; ?>"</script>

You can also wrap your HTML code into a PHP variable care about the ". You will need to escape it or us single quote instead:

<?php
$myHTML = "<script> window.location=\"mylocation.com\";</script>";
$myHTML = "<script> window.location= 'mylocation.com' ;</script>";
...
echo $myHTML;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Btw, I wouldn't recommend to merge HTML and PHP. There are several technique (like MVC model) in order to separate actions from visual. But this is only my opinion.

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.