Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boychawin/fba68d2bbf6277643fbbbf642266bf0c to your computer and use it in GitHub Desktop.
Save boychawin/fba68d2bbf6277643fbbbf642266bf0c to your computer and use it in GitHub Desktop.
สร้างรายงานด้วย กราฟแท่ง กราฟวงกลม ด้วย canvasjs & PHP
<?php
//โค้ดเชื่อมต่อฐานข้อมูลเอาไปปรับใช้เอานะครับ
define('NAME', "your-db");//ใส่ชื่อฐานข้อมลของท่าน
define("USER", "your-username");
define("PASS", "your-password");
define("HOST", "your-hostname");
$db = new mysqli(HOST, USER, PASS, NAME);
$db->set_charset("utf8");
$dataPoints = array();
$result = mysqli_query($db, "
SELECT COUNT(column1) AS x, y
FROM table
GROUP BY column2 ");
while($row = mysqli_fetch_array($result))
{
array_push($dataPoints, array("label"=> $row['x'], "y"=> $row['y']));
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function() {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title: {
text: "PHP Column Chart from Database"
},
data: [{
type: "column", //change type to bar, line, area, pie, etc
// ถ้าต้องการเปลี่ยนจากกราฟแท่งเป็นกราฟแผนภูมิวงกลม ให้เปิด คอมเมนต์ ด้านล่างนี้และเปลี่ยน จาก type: "column" เป็น type: "pie"
// type: "pie",
// yValueFormatString: "#,##0.00\"%\"",
// indexLabel: "{label} ({y})",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
@boychawin
Copy link
Author

boychawin commented Dec 19, 2020

//สำหรับคนที่เขียนแบบ PHP PDO ตาม link ด้านล่างนี้เลย
https://canvasjs.com/php-charts/chart-data-from-database/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment