I have a php code returning this data from mysql [8,430], [8,430], [8,380], [8,380], [8,430]
Want to insert it in to this JavaScript data array, cant figure it out how.
<?php
$link = mysql_connect('tankStatus.db.numbers.hostedresource.com', 'username', 'password')
or die('Could not connect: ' . mysql_error());
mysql_select_db('tankStatus') or die('Could not select database');
$dataArray=array();
$dateArray=array();
$in=0;
//get data from database
$sql="SELECT * FROM Additives ";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$dataArray[$in]=$row["Calcium"];
$dateArray[$in]=$row["pH"];
$in++;
}
$arrayLenght = count($dataArray);
for($x = 0; $x < $arrayLenght; $x++) {
echo "{$dateArray[$x]},";
echo "{$dataArray[$x]}";
if($x < $arrayLenght-1){
echo ", ";
}
}
}
?>will return 8,400, 8,420, 8,430, 8,430, 8,380, 8,380, 8,430
// Graph Data ##############################################
var graphData = [{
// Visits
data: [php data inserted here],
color: '#71c73e'
}, {
// Returning Visits
data: [ [6, 500], [7, 600], [8, 550], [9, 600], [10, 800], [11, 900], [12, 800], [13, 850], [14, 830], [15, 1000] ],
color: '#77b7c5',
points: { radius: 4, fillColor: '#77b7c5' }
}
];
</div>
It's best to use JSON to get data from PHP to JavaScript:
PHP: (get_data.php)
$formatted_data = array();
foreach($dataArray as $in => $ph){
$formatted_data[] = array($in, $ph);
}
echo(json_encode($formatted_data)); exit();
JavaScript and jQuery:
$.ajax({
dataType: "json",
url: get_data.php,
success: function(data){
alert(data);
}
});
Either luck of experience or just don't get it but I couldn't use your answer. Added the mysql php code to my main page and formatted the variable as the graph expected.
//part of php mysql
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$dataArray[$in]=$row["Calcium"];
$dateArray[$in]=$row["pH"];
$in++;
}
//end
//part og graph javascript
graphData = <?php echo "[ "; $arrayLenght = count($dataArray);
for($x = 0; $x < $arrayLenght; $x++) {
echo "[{$dateArray[$x]},";
echo "{$dataArray[$x]}]";
if($x < $arrayLenght-1){
echo ", ";
}
}
echo " ]";
?>;
//end
//result
graphData = [ [8,400], [7,420], [7,430], [8,430], [8,380], [8,380], [8,430] ];
//end
</div>
It looks to me that you want your end result data to be an array of arrays. So I would suggest formatting your result as such where you parse your query result:
$array_of_arrays = [];
while ($row = mysql_fetch_assoc($result)) {
$array_of_arrays[$in++] = [$row["pH"], $row["Calcium"]];
}
You may then echo the JSON encoded array of arrays into your JavaScript:
data: <?php echo json_encode($array_of_arrays); ?>,