Skip to main content
se añadieron 905 caracteres en el cuerpo
Origen Enlace
J. Mick
  • 103
  • 2
  • 16
  • 41
$stmt = $con->prepare("SELECT YEAR(order_date) AS year_report,
                            MONTHNAME(order_date) AS month_report,
                            sum(quantity) AS quantity,
                            sum(price) AS price,
                            order_date
                        FROM tbl_order
                        WHERE id_manager=6
                        GROUP BY YEAR(order_date), MONTHNAME(order_date)
                        ORDER BY YEAR(order_date), MONTHNAME(order_date)");
$stmt->execute();
$stmt->store_result();
$dateArray = [];//array();
$dateArray2 = [];
$stmt->bind_result(
    $year_report,
    $month_report,
    $quantity,
    $price,
    $order_date
);
while ($stmt->fetch()) {
    $dateArray[] = $order_date;
    $dateArray2[] = $month_report;
}
$stmt = $con->prepare("SELECT YEAR(order_date) AS year_report,
                            MONTHNAME(order_date) AS month_report,
                            sum(quantity) AS quantity,
                            sum(price) AS price,
                            order_date
                        FROM tbl_order
                        WHERE id_manager=6
                        GROUP BY YEAR(order_date), MONTHNAME(order_date)
                        ORDER BY YEAR(order_date), MONTHNAME(order_date)");
$stmt->execute();
$stmt->store_result();
$dateArray = [];//array();
$dateArray2 = [];
$stmt->bind_result(
    $year_report,
    $month_report,
    $quantity,
    $price,
    $order_date
);
while ($stmt->fetch()) {
    $dateArray[] = $order_date;
    $dateArray2[] = $month_report;
}
se añadieron 37 caracteres en el cuerpo
Origen Enlace
J. Mick
  • 103
  • 2
  • 16
  • 41
$stmt = $con->prepare("SELECT YEAR(order_date) AS year_report,
                            MONTH(order_date) AS month_report,
                            DAY(order_date) AS day_report,
                            sum(quantity) AS quantity,
                            sum(price) AS price,
                            order_date
                        FROM tbl_order
                        WHERE id_seller=6
                        GROUP BY YEAR(order_date), DAY(order_date), MONTH(order_date)
                        ORDER BY YEAR(order_date), DAY(order_date), MONTH(order_date)");
$stmt->execute();
$stmt->store_result();
$outcome = array();
$stmt->bind_result(
    $outcome['year_report'],
    $outcome['month_report'],
    $outcome['day_report'],
    $outcome['quantity'],
    $outcome['price'],
    $outcome['order_date']
);
while ($stmt->fetch()) {
    echo json_encode($outcome);
}

Actualización

Realizando intentos he realizado la siguiente modificaciones, aún estoy muy lejos de conseguir los datos de: const day, const week, const month pero de la siguiente manera he obtenido en la parte inferior los meses:

const dateArray = <?php echo json_encode($dateArray); ?>;
const dateChart = dateArray.map((day, index) => {
    let dayjs = new Date(day);
    console.log(dayjs);
    return dayjs.setHours(0,0,0,0);
})

//console.log(dateChart);
//console.log(day);
// setup 
const data = {
  //labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  //labels: dateChart,
  datasets: [{
    label: 'Weekly Sales',
    data: dateChart,

Es decir prácticamente tengo los datos x: faltarían los datos y: curiosamente probé lo siguiente pero no funcionó:

data: [dateChart, 10, 12, 18, 20],

Nota:los datos en y: van las cantidades de artículos vendidos de la variable $quantity adicional me gustaría agregar los ingresos totales que se los obtiene de la variable $price

$stmt = $con->prepare("SELECT YEAR(order_date) AS year_report,
                            MONTH(order_date) AS month_report,
                            DAY(order_date) AS day_report,
                            sum(quantity) AS quantity,
                            sum(price) AS price,
                            order_date
                        FROM tbl_order
                        WHERE id_seller=6
                        GROUP BY YEAR(order_date), DAY(order_date), MONTH(order_date)
                        ORDER BY YEAR(order_date), DAY(order_date), MONTH(order_date)");
$stmt->execute();
$stmt->store_result();
$outcome = array();
$stmt->bind_result(
    $outcome['year_report'],
    $outcome['month_report'],
    $outcome['day_report'],
    $outcome['quantity'],
    $outcome['price'],
    $outcome['order_date']
);
while ($stmt->fetch()) {
    echo json_encode($outcome);
}

Actualización

Realizando intentos he realizado la siguiente modificaciones, aún estoy muy lejos de conseguir los datos de: const day, const week, const month pero de la siguiente manera he obtenido en la parte inferior los meses:

const dateArray = <?php echo json_encode($dateArray); ?>;
const dateChart = dateArray.map((day, index) => {
    let dayjs = new Date(day);
    console.log(dayjs);
    return dayjs.setHours(0,0,0,0);
})

//console.log(dateChart);
//console.log(day);
// setup 
const data = {
  //labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  //labels: dateChart,
  datasets: [{
    label: 'Weekly Sales',
    data: dateChart,

Es decir prácticamente tengo los datos x: faltarían los datos y: curiosamente probé lo siguiente pero no funcionó:

data: [dateChart, 10, 12, 18, 20],

Nota:los datos en y: van las cantidades de artículos vendidos de la variable $quantity adicional me gustaría agregar los ingresos totales que se los obtiene de la variable $price

Origen Enlace
J. Mick
  • 103
  • 2
  • 16
  • 41

¿Cómo pasar datos json a chart.js?

Ya tengo preparada mi consulta para tener ventas por dia, por mes y por año, ahora esta general pero solo es de agregar condición WHERE o dejar individual la consulta por dia, mes y año:

$stmt = $con->prepare("SELECT YEAR(order_date) AS year_report,
                            MONTH(order_date) AS month_report,
                            DAY(order_date) AS day_report,
                            sum(quantity) AS quantity,
                            sum(price) AS price,
                            order_date
                        FROM tbl_order
                        WHERE id_seller=6
                        GROUP BY YEAR(order_date), DAY(order_date), MONTH(order_date)
                        ORDER BY YEAR(order_date), DAY(order_date), MONTH(order_date)");
$stmt->execute();
$stmt->store_result();
$outcome = array();
$stmt->bind_result(
    $outcome['year_report'],
    $outcome['month_report'],
    $outcome['day_report'],
    $outcome['quantity'],
    $outcome['price'],
    $outcome['order_date']
);
while ($stmt->fetch()) {
    echo json_encode($outcome);
}

Y manualmente ya he preparado mi gráfica usando la librería chartjs:

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-- 3.9.1-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js" type="text/javascript"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js" type="text/javascript"></script>
<div class="chartBox">
    <canvas id="myChart" width="400" height="400"></canvas>
    <button onclick="timeFrame(this)" value="day">Day</button>
    <button onclick="timeFrame(this)" value="week">Week</button>
    <button onclick="timeFrame(this)" value="month">Month</button>
</div>
<script>
    const day = [
        { x: Date.parse('2021-11-01 00:00:00 GMT+0800'), y: 18 },
        { x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 12 },
        { x: Date.parse('2021-11-03 00:00:00 GMT+0800'), y: 1 }
    ];
    const week = [
        { x: Date.parse('2021-10-31 00:00:00 GMT+0800'), y: 18 },
        { x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 87 },
        { x: Date.parse('2021-11-03 00:00:00 GMT+0800'), y: 10 }
    ];
    const month = [
        { x: Date.parse('2021-10-31 00:00:00 GMT+0800'), y: 18 },
        { x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 87 },
        { x: Date.parse('2021-12-03 00:00:00 GMT+0800'), y: 10 }
    ];

    console.log(day);
    // setup 
    const data = {
      //labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: day,
        //data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1
      }]
    };

    // config 
    const config = {
      type: 'bar',
      data,
      options: {
        scales: {
            x: {
                type: 'time',
                time: {
                    unit: 'month'
                }
            },
          y: {
            beginAtZero: true
          }
        }
      }
    };

    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );
    function timeFrame(period) {
        //console.log(period)
        //console.log(period.value)
        if(period.value == 'day') {
            myChart.config.options.scales.x.time.unit = period.value;
            myChart.config.data.datasets[0].data = day;
        }
        if(period.value == 'week') {
            myChart.config.options.scales.x.time.unit = period.value;
            myChart.config.data.datasets[0].data = week;
        }
        if(period.value == 'month') {
            myChart.config.options.scales.x.time.unit = period.value;
            myChart.config.data.datasets[0].data = month;
        }
        myChart.update();
    }
</script>

Lo que no entiendo es cómo puedo pasar mis datos json de mi consulta a estos parámetros de JavaScript que la funcionalidad chart.js espera:

const day = [
    { x: Date.parse('2021-11-01 00:00:00 GMT+0800'), y: 18 },
    { x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 12 },
    { x: Date.parse('2021-11-03 00:00:00 GMT+0800'), y: 1 }
];
const week = [
    { x: Date.parse('2021-10-31 00:00:00 GMT+0800'), y: 18 },
    { x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 87 },
    { x: Date.parse('2021-11-03 00:00:00 GMT+0800'), y: 10 }
];
const month = [
    { x: Date.parse('2021-10-31 00:00:00 GMT+0800'), y: 18 },
    { x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 87 },
    { x: Date.parse('2021-12-03 00:00:00 GMT+0800'), y: 10 }
];

¿Me pueden explicar cómo pasar dicha información a mi gráfico?