0

I'm working on a project that has a list of map markers. I'd like to pass data from a php database to values for the map. The mapping section of the code uses javascript. When it's manually entered, the javascript for the markers should look like this:

    var locations = [
         [
          "Place 0",
          47.06330, -102.34702,
          0,
          "",
          "",
          "",
          ""],
         [
          "Place 2",
          -27.37025, 133.44892,
          1,
          "",
          "",
          "",
          "found"],
      ];

I've tried using echo statements. Here's the combo of mysqli and javascript that I tried...

    var locations = [
    <?php
        while($res = mysqli_fetch_array($result)) {
            echo "[";
            echo "'".$res['name']."',";
            echo "".$res['lat'].", ".$res['lng'].",";
            echo "".$res['id'].",";
            echo "'',";
            echo "'',";
            echo "'',";
            echo "''],";
        }
    ?>
    ];

It doesn't give me any errors, but the markers don't show up on the map so it doesn't appear to be working. I'm using mysqli statements elsewhere in the html code and it's connecting properly, so I know that's not the problem. I've looked at several other posts about combining php and javascript, but its still not clear to me how to fix this issue. Any guidance is greatly appreciated!

1 Answers1

1

Rather than trying to output Javascript structures directly, create a PHP array with the appropriate structure and then output json_encode($array). In your case:

$locations = array();
while($res = mysqli_fetch_assoc($result)) {
    $locations[] = array($res['name'], $res['lat'], $res['lng'], $res['id'], '', '', '', '');
}
echo "var location = " . json_encode($locations) . ";";
Nick
  • 138,499
  • 22
  • 57
  • 95
  • @YourCommonSense And the downvote was because??? – Nick Nov 09 '19 at 05:43
  • I don't see any need for the `mysqli_fetch_array`, you are only retrieving the associative values, so `foreach($result as $res)` would be enough. – Dharman Nov 09 '19 at 17:36
  • 1
    @Dharman you are correct; I have changed to `fetch_assoc`. I personally don't like iterating the `mysqli_result` object as I think it can make the code confusing to someone who comes along later and looks at it. My personal preference is for the OOP form `$res = $result->fetch_xxx()` but I like to keep my answers consistent with OP's usage – Nick Nov 09 '19 at 22:08
  • Fantastic! This worked like a charm. Thank you so much. –  Nov 11 '19 at 20:44