0

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:

  1. Here is the SQL query:

    $sql = "SELECT COUNT(State) FROM `mytable`";
    $sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
    
  2. Here is how I pass the result into an array

     <? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..**  }
    
    <?php $js_array = json_encode($myvar['0']);?>
    
  3. Here is where I need to pass the data:

    .forEach(function(d){ 
        var     kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, //  No of customers in that state
                kpi02= .....
    
                sampleData[d]={kpi01, kpi02}; 
        });
    

Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?

10
  • you cannot do in .js file but can be done in .php or .html files Commented Dec 12, 2016 at 17:57
  • 1
    You'll need to use an AJAX call to a PHP file that handles the server side processing you need. PHP runs server side and runs BEFORE JavaScript, which runs client side. Commented Dec 12, 2016 at 17:58
  • Sidenote: your sql query is kind of pseudo to me (missing a quote) and that mysqli_error function requires db connection as an argument. Commented Dec 12, 2016 at 17:59
  • 1
    ok Samantha, I added the missing quote in an edit since it was throwing off syntax highlighting ;-) details details, eh? lol I'm just a perfectionist that way. Commented Dec 12, 2016 at 18:00
  • 1
    Yes that would be my solution. But thats not necessarily an easy solution either Commented Dec 12, 2016 at 18:07

1 Answer 1

2

Don't mess around with trying to generate a bunch of variables with numbers in their names.

Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.

 <?php
     $my_array = [];
     while($myvar=mysqli_fetch_array($sql_result)) {
         $my_array[] = $myvar;
     }
     $js_array = json_encode($my_array);
 ?>
 <script>
 var javascript_array = <?php echo $js_array; ?>;
 </script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.