I have a table with data of several metals and I need to get this data to use on my page, but I can not get all of it, only the first one works.
Code:
$link = mysqli_connect("localhost", "root", "", "metais");
$result = mysqli_query($link, "SELECT * FROM historical_data ORDER BY ID DESC LIMIT 2");
$cobre = "[";
while($array_cobre = mysqli_fetch_array($result)){
$d1 = explode("-", $array_cobre['data']);
$cobre .= "{x: new Date(".$d1['0'].", ".($d1['1'] - 1).", ".$d1['2']."), y: ".$array_cobre['copper']."},";
}
echo $cobre .= "]";
$aluminio = "[";
while($array_aluminio = mysqli_fetch_array($result)){
$d1 = explode("-", $array_aluminio['data']);
$aluminio .= "{x: new Date(".$d1['0'].", ".($d1['1'] - 1).", ".$d1['2']."), y: ".$array_aluminio['aluminium']."},";
}
echo $aluminio .= "]";
$chumbo = "[";
while($array_chumbo = mysqli_fetch_array($result)){
$d1 = explode("-", $array_chumbo['data']);
$chumbo .= "{x: new Date(".$d1['0'].", ".($d1['1'] - 1).", ".$d1['2']."), y: ".$array_chumbo['lead']."},";
}
echo $chumbo .= "]";
Output:
[{x: new Date(2016, 2, 25), y: 493100},{x: new Date(2016, 2, 24), y: 493100},]
[]
[]
New Array:
$itens = [];
while($array = mysqli_fetch_array($result)){
$d1 = explode("-", $array['data']);
$itens['cobre'][] = sprintf("{x: new Date(%s, %s, %s), y: %s}", $d1[0], $d1[1]-1, $d1[2], $array['copper']);
$itens['aluminio'][] = sprintf("{x: new Date(%s, %s, %s), y: %s}", $d1[0], $d1[1], $d1[2], $array['aluminium']);
$itens['chumbo'][] = sprintf("{x: new Date(%s, %s, %s), y: %s}", $d1[0], $d1[1]-1, $d1[2], $array['lead']);
}
echo json_encode($itens);
New output (Array):
{
"cobre":["{x: new Date(2016, 2, 25), y: 493100}","{x: new Date(2016, 2, 24), y: 493100}"],
"aluminio":["{x: new Date(2016, 03, 25), y: 146950}","{x: new Date(2016, 03, 24), y: 146950}"],
"chumbo":["{x: new Date(2016, 2, 25), y: 175500}","{x: new Date(2016, 2, 24), y: 175500}"]
}
How do I get each metal separately and play on the variable I'm going to use?
echo json_encode($itens['cobre']);
echo json_encode($itens['aluminio']);
echo json_encode($itens['chumbo']);