Doubt about highcharts and php

1

For styling a web page, I often use the highcharts graphics with information from a mysql database via php. For those unfamiliar with highcharts, here's a sample code below.

Highcharts.chart('minhadiv', {
chart: {
    type: 'bar'
},

xAxis: {
    categories: ['Categoria 1', 'Categoria 2', 'Categoria 3'],
},
series: [{
    name: 'Informação',
    data: [1, 2, 3]

}]
});

This code returns me a graph like this:

Ialwaysmakethephpconnectionwithmysqlwithinthedatafield,anditissuccessful.HereisanexampleofansqlconnectionI'veusedbefore:

data:[<?php$mysqli=newmysqli('servidor','usuario','senha','banco');$sql=$mysqli->query("SELECT minhacoluna from minhatabela");
                     ?>
                    <?php while ($result = mysqli_fetch_array($sql)) {?>
                      <?php echo $result["minhacoluna"]?>,

                    <?php } ?>],

The problem is that now I needed to make this sql connection in both the data field and the categories field, since the categories can change according to my database. When trying to put a php code like the one I normally use, I get no result. How to proceed in this case?

    
asked by anonymous 24.05.2018 / 13:17

1 answer

0

You can do this to display a chart with the categories as it is in the database.

Records in the Database:

Codeinphptofeedthechart:

$mysqli=newmysqli('servidor','usuario','senha','banco');//Aquivocêpodefazerumselectalimentandonormalumaváriavelcomascategoriasaserexibida$categories=array();$sql=$mysqli->query("SELECT nome from categorias");
while ($result = mysqli_fetch_array($sql)) {
    $categories[] = $result['nome'];
}

// Select para pegar os dados da tabela
$sql = $mysqli->query("SELECT coluna, valor from grafico");

$valores = array();

// while dos registros alimentando um array
while ($result = mysqli_fetch_array($sql)) {
    $valores[$result['coluna']][] = floatval($result['valor']);
}

// aqui irá ser colocado a váriavel que foi alimentada por array no while acima
// para deixar no padrão que o highcharts reconhece
foreach($valores as $key => $value)
{
    $series[] = array('name' => utf8_encode($key), 'data' => array_values($value));
}   

Highcharts js code:

Highcharts.chart('container', {
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Chart title'
    },
    xAxis: {
        categories: <?=json_encode($categories); ?> // Transforma array em json para mostrar as categorias
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total fruit consumption'
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: <?=json_encode($series); ?> // Transforma array em json para mostrar as informações do gráfico
});

Result:

    
24.05.2018 / 16:20