Portada » Lenguaje PHP » Gráfico de líneas usando Chart.js con PHP

Gráfico de líneas usando Chart.js con PHP

Gráfico de líneas usando Chart.js con PHP. Las estadísticas siempre son vitales para cualquier sistema porque gráficamente podemos apreciar el estado de las ventas, compras, registros, etc. Sin embargo, implementarlas en nuestro proyecto suele ser un poco complicado.

Recursos para Gráficos Chart de líneas

En este articulo veremos cómo realizar Grafico de líneas usando lo siguiente:

Pasos para integrar Chart gráficos

Además, implementaremos un CDN para Bootstrap y jQuery para no saturar el servidor, entonces se necesitará acceso a internet para que funcionen. porque son ficheros externos.

Gráfico de líneas usando Chart.js con PHP
Gráfico de líneas usando Chart.js con PHP

Gráfico de líneas usando Chart: INSTALACIÓN

Creación de base de datos

Se necesitará de una base de datos y le llamaremos «lineas_db«, pero puede ser cualquier otro nombre que quieran darle.

Usaremos MySQL para almacenar la información y pueden usar phpMyAdmin u otro gestor.

CREATE TABLE `tbl_ventas` (
`ventas_id` int(11) NOT NULL,
`monto` double NOT NULL,
`venta_fecha` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `tbl_ventas` (`ventas_id`, `monto`, `venta_fecha`) VALUES
(8, 100, '2020-01-01'),
(9, 55, '2019-01-01'),
(10, 200, '2020-02-02'),
(11, 55, '2019-02-02'),
(12, 175, '2020-03-03'),
(13, 150, '2019-03-03'),
(14, 150, '2020-04-04'),
(15, 85, '2019-04-04'),
(16, 99, '2020-04-04'),
(17, 20, '2019-04-04'),
(18, 180, '2020-05-05'),
(19, 70, '2019-05-05'),
(20, 225, '2019-06-06'),
(21, 150, '2020-06-06'),
(22, 120, '2020-07-07'),
(23, 55, '2019-07-07'),
(24, 199, '2020-08-08'),
(25, 45, '2019-08-08'),
(26, 130, '2020-09-09'),
(27, 75, '2019-09-09'),
(28, 300, '2019-10-10'),
(29, 35, '2019-10-10'),
(30, 250, '2019-11-11'),
(31, 20, '2019-11-11'),
(32, 220, '2020-08-12'),
(33, 200, '2019-12-12'),
(34, 45, '2019-01-05'),
(35, 50, '2020-10-02'),
(36, 300, '2020-10-05'),
(37, 100, '2020-10-06');

ALTER TABLE `tbl_ventas`
ADD PRIMARY KEY (`ventas_id`);

ALTER TABLE `tbl_ventas`
MODIFY `ventas_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;

Como pueden apreciar el código anterior posee la tabla y los registros necesarios para que el ejemplo funcione correctamente. Sin embargo, cuando descarguen las consultas SQL estarán en un archivo llamado «lineas_db.sql«.

Este fichero lo pueden importar a phpMyAdmin.

ESTRUCTURA DE FICHEROS

Estructura de archivos chart lineas
Estructura de archivos chart lineas

A) Declarar Librerías externas y  código HTML

Fichero Index.php

Cuando el usuario acceda al script, este será el primer fichero en cargar porque mostrara el grafico de líneas y además será el encargado de mostrar un formulario para ingresar información a nuestra base de datos. Además, contiene el código JavaScript que necesita nuestro gráfico de líneas.

<!DOCTYPE html>
<html>
<head>
<title>Gráfico de líneas usando Chart.js con PHP - BaulPHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- ChartJS -->
<script src="chart.js/Chart.js"></script>
</head>
<body>
<div class="container">
<h1 class="page-header text-left">Gráfico de líneas usando Chart.js con PHP</h1>
<div class="row">
<form class="navbar-form navbar-left" method="POST" action="agregar_ventas.php">
<div class="form-group">
<input name="monto" type="text" class="form-control" placeholder="Monto">
</div>
<div class="form-group">
<input name="venta_fecha" type="date" class="form-control" placeholder="Fecha">
</div>
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Agregar Venta </button>
</form>

</div><!-- /.row -->
<div class="row">

<div class="col-md-10">
<div class="box box-success">
<div class="box-header with-border">
<?php
$year = date('Y');
?>
<h3 class="box-title">Reporte de ventas (<?php echo $year-1; ?> vs <?php echo $year; ?>)</h3>

</div>
<div class="box-body">
<div class="chart">
<canvas id="lineChart" style="height:250px"></canvas>
</div>
</div>
<!-- /.box-body -->
</div>
</div>
</div>
</div>
<?php include('proceso.php'); ?>
<script>
$(function () {
var lineChartData = {
labels : ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre', 'Octubre', 'Noviembre', 'Diciembre'],
datasets: [
{
label : 'Año Previo',
fillColor : 'rgba(210, 214, 222, 1)',
strokeColor : 'rgba(210, 214, 222, 1)',
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data : [ "<?php echo $pjan; ?>",
"<?php echo $pfeb; ?>",
"<?php echo $pmar; ?>",
"<?php echo $papr; ?>",
"<?php echo $pmay; ?>",
"<?php echo $pjun; ?>",
"<?php echo $pjul; ?>",
"<?php echo $paug; ?>",
"<?php echo $psep; ?>",
"<?php echo $poct; ?>",
"<?php echo $pnov; ?>",
"<?php echo $pdec; ?>" 
]
},
{
label : 'Este año',
fillColor : 'rgba(60,141,188,0.9)',
strokeColor : 'rgba(60,141,188,0.8)',
pointColor : '#3b8bba',
pointStrokeColor : 'rgba(60,141,188,1)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data : [ "<?php echo $tjan; ?>",
"<?php echo $tfeb; ?>",
"<?php echo $tmar; ?>",
"<?php echo $tapr; ?>",
"<?php echo $tmay; ?>",
"<?php echo $tjun; ?>",
"<?php echo $tjul; ?>",
"<?php echo $taug; ?>",
"<?php echo $tsep; ?>",
"<?php echo $toct; ?>",
"<?php echo $tnov; ?>",
"<?php echo $tdec; ?>" 
]
}
]
}

var lineChartCanvas = $('#lineChart').get(0).getContext('2d')
var lineChart = new Chart(lineChartCanvas)
var lineChartOptions = {
//Boolean - If we should show the scale at all
showScale : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : false,
//String - Colour of the grid lines
scaleGridLineColor : 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines : true,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.3,
//Boolean - Whether to show a dot for each point
pointDot : false,
//Number - Radius of each point dot in pixels
pointDotRadius : 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a color
datasetFill : true,
//String - A legend template
legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].lineColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio : true,
//Boolean - whether to make the chart responsive to window resizing
responsive : true
}

lineChartOptions.datasetFill = false
lineChart.Line(lineChartData, lineChartOptions)

})
</script>
</body>
</html>

B) Código PHP insertar registros SQL

Fichero agregar_ventas.php

Este es nuestro código PHP con la adición de datos a nuestra base de datos que fue enviado por el formulario. Sin embargo, registrara el monto y la fecha, datos que son vitales para nuestro grafico estadístico.

<?php
// Declaramos el fichero de conexión
include_once("config.php");

//Variables enviadas por el formulario
$monto = $_POST['monto'];
$venta_fecha = $_POST['venta_fecha'];

// Datos de estado de cuenta preparados
$query = $db->prepare("INSERT INTO `tbl_ventas` (`monto`, `venta_fecha`)
VALUES (:monto, :venta_fecha)");
$query->bindParam(":monto", $monto);
$query->bindParam(":venta_fecha", $venta_fecha);
// Ejecuta SQL
$query->execute();

// redireccion a URL
header("Location: index.php");
/*echo("<script>location.href = index.php';</script>");*/
?>

C) Script PHP de consultas SQL

Archivo proceso.php

Tendrá un rol importante y contiene nuestros datos que vamos a utilizar en nuestro chart.js para hacer datos estadísticos en forma de gráfico de líneas. Además, realiza dos consultas a la base de datos para mostrar ventas del año anterior y el presente año y lo devuelve en un array.

Esta información, será implementada en la librería CHART.JS para que pueda crear el grafico dinámico.

<?php
// Declaramos el fichero de conexión
include_once("config.php");

$year = date('Y');
$total=array();
for ($month = 1; $month <= 12; $month ++){

$query = $db->prepare("select sum(monto) as total from tbl_ventas where month(venta_fecha)='$month' and year(venta_fecha)='$year'");
$query->execute();
$row = $query->fetch();
$total[]=$row['total'];

}

$tjan = $total[0];
$tfeb = $total[1];
$tmar = $total[2];
$tapr = $total[3];
$tmay = $total[4];
$tjun = $total[5];
$tjul = $total[6];
$taug = $total[7];
$tsep = $total[8];
$toct = $total[9];
$tnov = $total[10];
$tdec = $total[11];

$pyear = $year - 1;
$pnum=array();

for ($pmonth = 1; $pmonth <= 12; $pmonth ++){ 
$pquery = $db->prepare("select sum(monto) as ptotal from tbl_ventas where month(venta_fecha)='$pmonth' and year(venta_fecha)='$pyear'");
$pquery->execute();
$prow = $pquery->fetch();
$ptotal[]=$prow['ptotal'];
}

$pjan = $ptotal[0];
$pfeb = $ptotal[1];
$pmar = $ptotal[2];
$papr = $ptotal[3];
$pmay = $ptotal[4];
$pjun = $ptotal[5];
$pjul = $ptotal[6];
$paug = $ptotal[7];
$psep = $ptotal[8];
$poct = $ptotal[9];
$pnov = $ptotal[10];
$pdec = $ptotal[11];
?>

D) Conexión con MySQL

Config.php

Por último, tenemos al fichero que será el encargado de realizar la conexión con la base de datos usando PDO la conexión mas recomendada.

<?php
$host = "localhost";
$dbname = "lineas_db";
$username = "root";
$password = "";

// Conexión PDO 
try {
// Cree un nuevo objeto PDO y guárdelo en la variable $ db
$db = new PDO("mysql:host={$host};dbname={$dbname}", $username, $password);
// Configure el modo de error en PDO para mostrar inmediatamente las excepciones cuando haya errores
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exception){
die("Connection error: " . $exception->getMessage());
}
error_reporting(0);
?>

CONCLUSIÓN

  • Para este ejemplo usaremos la librería Chart.js que se incluye en el archivo descargable de este tutorial.
  • Hemos aprendido a crear un gráfico estadístico dinámico con PHP y MySQL usando librerías como el chart.js
  • También hemos aprendido a implementar PDO en nuestras consultas.

Espero que este tutorial les sirva para sus proyectos que estén realizando.

¿De cuánta utilidad te ha parecido este contenido?

¡Haz clic en una estrella para puntuarlo!

Promedio de puntuación 5 / 5. Recuento de votos: 2

Hasta ahora, ¡no hay votos!. Sé el primero en puntuar este contenido.

Scroll al inicio
Esta web utiliza cookies propias para su correcto funcionamiento. Contiene enlaces a sitios web de terceros con políticas de privacidad ajenas que podrás aceptar o no cuando accedas a ellos. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos.
Privacidad