CREATE TABLE `score` (
`playerid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`score` int(11) DEFAULT '0',
PRIMARY KEY (`playerid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `score` VALUES (1,10),(2,40),(3,20),(4,9),(5,20);
Create a new project folder and name it chartjs. Note! Feel free to name your project as per your choice. Inside the chartjs project folder create a subfolder and name it js. This will hold all the javascript files.
Copy the Chart.min.js and jquery.min.js files inside the js folder that we created inside the chartjs project folder. And create an app.js file inside the js folder. This will contain all the javascript code that we are going to write for this project.
Create a new file data.php inside the chartjs folder. This file is going to contain php code that will fetch data from the score table and display it in JSON format.
File: data.php
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root123');
define('DB_NAME', 'mydb');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);