php – how to send 2d array javascript coordinates to mysql?-ThrowExceptions

Exception or error:

I created an 2d array to store my coordinates(longitude, latitude).

var nbPoints = 0;

var gps = new Array(20);

for (var i = 0; i < gps.length; i++) {
 gps[i] = new Array(2);
}

with this code i am able to get every coordinates with each click and store it on my 2d array.

map.on('click', function(e) {

    lon = e.lngLat.lng;
    lat = e.lngLat.lat;

    gps[nbPoints][0] = lon;
    gps[nbPoints][1] = lat; 

    nbPoints = nbPoints+1;
    console.log(lon,lat);

});

and finally i am trying to send every coord from my array to my database witch contain Id, Lon and Lat but it only send one coordinates.

$("#vol").click(function(e) //envoyer tous les coords vers bdd
  {
       for (var i = 0 ; i < nbPoints; i++) {

           posLon = gps[i][0];  
           posLat = gps[i][1];

        console.log("parcours: "+gps[i][0]+ " " +gps[i][1]);
    }

    $.ajax({
        type: "POST",
        url: "table.php",
        data: {
            'lon' : posLon,
            'lat' : posLat 
            },
        success: function(){
            console.log("OK");
        }
      });

  });

this is my PHP code.

<?php 

    $conn = mysqli_connect('localhost', 'root', '' , 'api');

    if (!$conn) 
   {

      die("Connection failed: ".mysqli_connect_error());

   }

     $lon = $_POST['lon'];
     $lat = $_POST['lat']; 

     $sql = "INSERT INTO coordonnes (lng, lat) VALUES('".$lon."','".$lat."')";
     if($conn->query($sql)) 
     {
       echo "Donnes Enregistrer";
     }
     else
     {
       echo $conn->error;
     }

 ?>
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *