How to Create Pie Chart in PHP

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


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

  `id` int(11) NOT NULL,
  `gender` varchar(255) DEFAULT NULL,
  `age` varchar(255) DEFAULT NULL

Step 2: Create config.php File.


// 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";
	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.

	include 'config.php';
	$query="SELECT * from school"	;
<!DOCTYPE html>
<html lang="en">
	<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">
	<div class="container">
		<div class="row">
			<div class="col-md-6">
				<h1 align="center">School Pie Chart Data</h1>
	 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      function drawChart() {
        var data = google.visualization.arrayToDataTable([

          	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,

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

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *