Note that there are some explanatory texts on larger screens.

plurals
  1. POFilling D3.js Pie Graph with SQL Query
    text
    copied!<p>I am currently using D3.js to make a pie graph. The data is stored in a MSSQL database, which is then converted to JSON using PHP. Here is my code that does that</p> <pre><code>&lt;?php // Server Name $myServer = "SRVR"; // Database $myDB = "TestDB"; // If using Windows Authentication, get rid of, "'UID'=&gt;$myUser, 'PWD'=&gt;$myPass, " // Notice that the latest driver uses sqlsrv rather than mssql $conn = sqlsrv_connect('Database'=&gt;$myDB)); // Change TestDB.vwTestData to YOURDB.dbo.YOURTABLENAME $sql = "SELECT col, SUM(num) AS 'value' FROM db GROUP BY col"; $result = array(); do { while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){ $result[] = $row; } } while ( sqlsrv_next_result($data) ); // This will output in JSON format if you try to hit the page in a browser echo json_encode($result); sqlsrv_free_stmt($data); sqlsrv_close($conn); ?&gt; </code></pre> <p>This works fine. I've tested it, and it outputs JSON in something like this:</p> <pre><code>[{"col":null,"value":247.9042254},{"col":"value1","value":16.8151576061},{"col":"value2","value":235.4833175609},{"col":"value3","value":2316.072432028},{"col":"value4","value":8904.4001532729}] </code></pre> <p>How can I put this in the graph? Here is my .js code</p> <pre><code>(function() { var width = 960, height = 500, radius = Math.min(width, height) / 2; var color = d3.scale.ordinal() .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]); var arc = d3.svg.arc() .outerRadius(radius - 10) .innerRadius(0); var pie = d3.layout.pie() .sort(null) .value(function(d) { return // Something goes here I assume }); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); d3.json("scripts/graphs/script.php", function(error, data) { data.forEach(function(d) { // Something needs to go here? }); var g = svg.selectAll(".arc") .data(pie(data)) .enter().append("g") .attr("class", "arc"); g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data.age); }); g.append("text") .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; }) .attr("dy", ".35em") .style("text-anchor", "middle") .text(function(d) { return d.data.age; }); }); })(); </code></pre> <p>If someone could help me out, that would be great. Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload