piechart

How to Create Pie Chart in PHP

Spread the love

Today we will learn how to make a pie chart in PHP.

To create a pie chart in PHP, we will first create a database, then we will create a table in it and we will show the value of that table in the pie chart.

Follow me Guys

Step 1: Create New Database and Table

Create a new chart named database

Then

Create a new table name it school and add some value to it


CREATE TABLE `age` (
  `id` int(11) NOT NULL,
  `gender` varchar(255) DEFAULT NULL,
  `age` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Step 2: Create config.php File.

 
<?php 

// Enter your Host, username, password, database below.
// I left password empty because i do not set password on localhost.
$connect=mysqli_connect('localhost','root','','chart') or die("connection failed : ".mysqli_connect_error());

if ($connect) {
	//echo "Connection Successfully";
}
else{
	echo "Sorry Some Mistakes is";
}
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

?>

Step 3: Create index.php File.

 
<?php 
	include 'config.php';
	$query="SELECT * from school"	;
	$result=mysqli_query($connect,$query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Pie Chart</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-md-6">
				<h1 align="center">School Pie Chart Data</h1>
			</div>
		</div>
	</div>
	 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['class','students'],

          <?php 
          	while ($row = mysqli_fetch_array($result)) {
          		
          		//echo "<pre>";print_r($row); die;
          		echo "['".$row["class"]."',".$row["students"]."],  ";
          	}
          ?>
        ]);
        var options = {
          title: 'School Data in chart',
         // pieHole: 0.4,
          is3d:true,
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));
        chart.draw(data, options);
      }
    </script>
    <div id="piechart" style="width: 100%; height: 500px;"></div>
</body>
</html>

Spread the love

Related Posts

Leave a Reply

Your email address will not be published.