The Code
PHP:
<?php
session_start();
if ($_SESSION['Username'] == "")
{
header('Location: Login.php');
}
?>
Java Script:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
//Google Stuff
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Element');
data.addColumn('number', 'Percentage');
data.addRows([
<?php
include 'php/dbh.php';
$Rows = array();
$sql = "SELECT * FROM Sales";
$Result = mysqli_query($conn, $sql);
if ($Result)
{
while ($row = mysqli_fetch_assoc($Result)) {
$Rows[] = $row;
}
}
$ListArray = array();
foreach ($Rows as $row)
{
asort($row);
$row = explode(",", $row['Products']);
$ListArray = $row;
}
$numItems = count($ListArray);
$i = 0;
foreach ($ListArray as $item)
{
$i2 = 0;
$Newitem = ltrim($item);
$sql2 = "SELECT * FROM submenus WHERE Name='".$Newitem."'";
$Result = mysqli_query($conn, $sql2);
if (!$Result)
{
print_r(mysqli_error($conn));
}
if ($Result)
{
while ($row = mysqli_fetch_assoc($Result))
{
$i2 = $row['Sales'];
}
}
if(++$i === $numItems)
{
echo "['".$item."',".$i2."]";
}
else
{
echo "['".$item."',".$i2."],";
}
}
?>
]);
// Set chart options
var options = {
title:'Sales',
titleTextStyle: {color: 'white', bold: true},
height:300,
backgroundColor: '#3a3939',
color: '#fff',
legend: {textStyle: {color: 'white'}},
hAxis: {gridlines: {color: 'black'}}};
// Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('SalesChar'));
chart.draw(data, options );
}
</script>
HTML:
<fieldset class="Sales">
<legend style="color: white;">Sales</legend>
<div id="SalesChar"/>
</fieldset>
How it works
The PHP Code just start a session and if the Username is == "" it will redirect to the login page.
The Java Script is Located in the header of a webpage and it simply load and draw rows, inside the data.addRows([]);
There is a PHP code that first gets a table called Sales, then for each row it will explode the column called products so it gets multiple string and then add it to a array then for each string it will get from another table called submenus then if everything goes right it will echo something like this ['Test', 2]
The Html is located in the body and it is only there because it is indicating where the chart should be drawn
What i want to know
i want to know if there is any way possible to make the PHP that is located inside the javascript more compact and more readable (i mean easier to understand) and take a less space.
I am open to any other suggestion