Issue on Sending Two Columns of MySQL to JSON in PHP

75 Views Asked by At

I am trying to load a two columns of a table(map) from MySQL database to JavaScript array using following ajax and PHP code and I am getting this in result:

{"0":"218.5149144","x":"218.5149144","1":"215.5990218","y":"215.5990218"}

<script>
$( document ).ready(function() {
    $("#submit").on("click",function(){
        $.ajax({
                type:"POST",
                url:"map.php",
                success: function (html) {
                    $('#message').html(html);
                }
        });
    });
});
</script>

<?PHP   
   define ( 'DB_HOST', 'localhost' );
   define ( 'DB_USER', 'root' );
   define ( 'DB_PASS', '' );
   define ( 'DB_NAME', 'test' );
   $con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
   $query = "SELECT x,y FROM app";
   $result = $con->->query($query)->fetch_array();
   echo json_encode($result);
 $con->close();

can you please let me know how I can modify my PHP to get the result like:

 [
   [ 218.5149144 , 215.5990218 ],
   [ 219.2915206 , 216.8274247 ],
   [ 254.5833588 , 311.9862023 ],
   [ 254.2178971 , 314.9889649 ]
 ];
1

There are 1 best solutions below

6
On BEST ANSWER
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'test' );
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$query = "SELECT x,y FROM app";
$results = $con->query($query);
$return = array();
if($results) {
while($row = $results->fetch_assoc()) {
    $return[] = array((float)$row['x'],(float)$row['y']);
}
}
echo json_encode($return);
$con->close();
?>