Sumeet Jaiswal Sumeet Jaiswal - 6 months ago 15
Javascript Question

My map data's are not getting stored in the mysql database using php

hey i am facing a problem of data not getting stored in the table which i created in mysql database. i have created 4 tables trip,Droute,Wroute,Troute
previously when i had only two tables trip and route my data were getting properly populated in the table but now as i want my data to be segregated as per travel modes so,now i am facing this problem.here's my code.
Thanks in advance.

<html>
<head>
<title></title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var routeArr = [];
var routeArr2 = [];
var routeArr3 = [];
var directionsDisplay; // The whole map rendering or displaying.
var globalResponse;
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs

google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({'draggable': true});
});

function GetRoute() {
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map (lat and long of kolkata)
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};

map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view

directionsDisplay.setMap(map); // Map view

directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View

source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;

var request = // variable request 1
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING // here driving is selected
};

var request2 = // variable request 2
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.WALKING // here WALKING is selected
};


var request3 = // variable request 3
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.TRANSIT // here TRANSIT is selected
};

directionsService.route(request, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
globalResponse = response;
routeArr = [];

for (i = 0; i < globalResponse.routes.length; i++) {

routeArr.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
}
var s = 'Possible routes are: <br />';
for (i = 0; i < routeArr.length; ++i) {

routeArr[i][0] = routeArr[i][0].trim();
routeArr[i][0] = routeArr[i][0].substring(0, routeArr[i][0].length - 3)
routeArr[i][1] = routeArr[i][1].split(' ');
if (routeArr[i][1].length == 2 && routeArr[i][1][1].charAt(0) == 'm') {
routeArr[i][1] = parseInt(routeArr[i][1][0]);
}
else if (routeArr[i][1].length == 4 && routeArr[i][1][1].charAt(0) == 'h') {
routeArr[i][1] = parseInt(routeArr[i][1][0]) * 60 + parseInt(routeArr[i][1][2]);
}
else {
routeArr[i][1] = parseInt(routeArr[i][1][0]) * 24 * 60 + parseInt(routeArr[i][1][2] * 60); //for day hour minutes,all calculation under mins
}
s += "Distance: " + routeArr[i][0] + ", " + "Duration: " + routeArr[i][1] + "<br />";

}

document.getElementById("dvDistance").innerHTML = s;
directionsDisplay.setDirections(response);


}
else
{
alert("Unable to find the distance via road(DRIVING).");
}
});



directionsService.route(request2, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
globalResponse = response;
routeArr2 = [];

for (i = 0; i < globalResponse.routes.length; i++) {

routeArr2.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
}
var s = document.getElementById("dvDistance").innerHTML;
for (i = 0; i < routeArr2.length; ++i) {

routeArr2[i][0] = routeArr2[i][0].trim();
routeArr2[i][0] = routeArr2[i][0].substring(0, routeArr2[i][0].length - 3)
routeArr2[i][1] = routeArr2[i][1].split(' ');
if (routeArr2[i][1].length == 2 && routeArr2[i][1][1].charAt(0) == 'm') {
routeArr2[i][1] = parseInt(routeArr2[i][1][0]);
}
else if (routeArr2[i][1].length == 4 && routeArr2[i][1][1].charAt(0) == 'h') {
routeArr2[i][1] = parseInt(routeArr2[i][1][0]) * 60 + parseInt(routeArr2[i][1][2]);
}
else {
routeArr2[i][1] = parseInt(routeArr2[i][1][0]) * 24 * 60 + parseInt(routeArr2[i][1][2] * 60); //for day hour minutes,all calculation under mins
}
s += "Distance: " + routeArr2[i][0] + ", " + "Duration: " + routeArr2[i][1] + "<br />";

}

document.getElementById("dvDistance").innerHTML = s;
directionsDisplay.setDirections(response);

}
else
{
alert("Unable to find the distance via road(WALKING).");
}
});



directionsService.route(request3, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
globalResponse = response;
routeArr3 = [];

for (i = 0; i < globalResponse.routes.length; i++) {

routeArr3.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
}
var s = document.getElementById("dvDistance").innerHTML;
for (i = 0; i < routeArr3.length; ++i) {

routeArr3[i][0] = routeArr3[i][0].trim();
routeArr3[i][0] = routeArr3[i][0].substring(0, routeArr3[i][0].length - 3)
routeArr3[i][1] = routeArr3[i][1].split(' ');
if (routeArr3[i][1].length == 2 && routeArr3[i][1][1].charAt(0) == 'm')
{
routeArr3[i][1] = parseInt(routeArr3[i][1][0]);
}
else if (routeArr3[i][1].length == 4 && routeArr3[i][1][1].charAt(0) == 'h')
{
routeArr3[i][1] = parseInt(routeArr3[i][1][0]) * 60 + parseInt(routeArr3[i][1][2]);
}
else
{
routeArr3[i][1] = parseInt(routeArr3[i][1][0]) * 24 * 60 + parseInt(routeArr3[i][1][2] * 60); //for day hour minutes,all calculation under mins
}
s += "Distance: " + routeArr3[i][0] + ", " + "Duration: " + routeArr3[i][1] + "<br />";

}

document.getElementById("dvDistance").innerHTML = s;
directionsDisplay.setDirections(response);

}
else
{
alert("Unable to find the distance via road(TRANSIT).");
}
//--------------------------------------------------------------------------------------------------------------------------------------
// Here's the AJAX request
var httpRequest;
if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject)
{ // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() { // here the function name that is designed to handle the response
if (httpRequest.readyState == 4 && httpRequest.status == 200) { //200 OK response code. // 4 is complete response received
alert(httpRequest.responseText);
}
};
httpRequest.open("POST", "testdb.php", true); // here true means asynchronously server is called,i.e,without page reloading
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("&source=" + source + "&destination=" + destination + "&sel=" + sel + "&i=" + i + "&routes=" + JSON.stringify(routeArr) + "&routes2=" + JSON.stringify(routeArr2) + "&routes3=" + JSON.stringify(routeArr3));


});

var sel = document.getElementById('modes').value; // which mode the user is preferring

}
</script>
<!--------------------------------------------------------------------------------------------------------------------------------------------------------->
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px"/>
&nbsp; Destination:
<input type="text" id="txtDestination" style="width: 200px"/>
&nbsp; Travel Mode:
<select id="modes">
<option value="driving">Driving</option>
<option value="transit">Transit</option>
<option value="walking" selected>Walking</option>
</select>
<br/>
<input type="button" value="Get Route" onclick="GetRoute()"/>
<hr/>
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>
</html>


here is my php file:

<?php

if(isset($_POST['source'], $_POST['destination'], $_POST['sel'], $_POST['i']) && count($_POST['routes']) && count($_POST['routes2']) && count($_POST['routes3']))
{
$routes_array = json_decode($_POST['routes'], true);
$routes_array2 = json_decode($_POST['routes2'], true);
$routes_array3 = json_decode($_POST['routes3'], true);
echo "Routes read";


$conn = new mysqli("localhost", "root", "", "test"); // Create connection

if ($conn->connect_error) // Check connection
{
die("Connection failed: " . $conn->connect_error);
}

$i = $_POST['i'];
$sel = $_POST['sel'];
$source = $_POST['source'];
$destination = $_POST['destination'];
$query = "INSERT INTO trip(source, destination, mode, num_routes) VALUES('{$source}', '{$destination}', '{$sel}', '{$i}')";
if($conn->query($query))
{

$trip_id = $conn->insert_id;
foreach($routes_array as $route)
{
$distance = $route[0];
$duration = $route[1];
$query = "INSERT INTO droute(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')"; //distance in km and duration in mins
$conn->query($query);
}
echo "Sumeet!!!Success";
}
else
{
echo "Something went wrong!!! Record couldn't be inserted";
}
if($conn->query($query))
{
$trip_id = $conn->insert_id;
foreach($routes_array2 as $route2)
{
$distance = $route2[0];
$duration = $route2[1];
$query = "INSERT INTO wroute(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')"; //distance in km and duration in mins
$conn->query($query);
}
echo "Sumeet!!!Success";
}
else
{
echo "Something went wrong!!! Record couldn't be inserted";
}
if($conn->query($query))
{
$trip_id = $conn->insert_id;
foreach($routes_array3 as $route3)
{
$distance = $route3[0];
$duration = $route3[1];
$query = "INSERT INTO troute(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')"; //distance in km and duration in mins
$conn->query($query);
}
echo "Sumeet!!!Success";
}
else
{
echo "Something went wrong!!! Record couldn't be inserted";
}
$conn->close();
}
?>

Answer

In your php file, you are executing query thrice, do you really want it that way? It will generate three different insert_id s for the same route. I guess this is what you want.

<?php

if(isset($_POST['source'], $_POST['destination'], $_POST['sel'], $_POST['i']) && count($_POST['routes']) && count($_POST['routes2']) && count($_POST['routes3']))
{
    $routes_array = json_decode($_POST['routes'], true);
    $routes_array2 = json_decode($_POST['routes2'], true);
    $routes_array3 = json_decode($_POST['routes3'], true);
    echo "Routes read";


    $conn = new mysqli("localhost", "root", "", "test");      // Create connection

    if ($conn->connect_error)                                   // Check connection
    {
         die("Connection failed: " . $conn->connect_error);
    }

    $i = $_POST['i'];
    $sel = $_POST['sel'];
    $source = $_POST['source'];
    $destination = $_POST['destination'];
    $query = "INSERT INTO trip(source, destination, mode, num_routes) VALUES('{$source}', '{$destination}', '{$sel}', '{$i}')";
    if($conn->query($query))
    {
        $route_count = 0;
        $trip_id = $conn->insert_id;
        foreach($routes_array as $route)
        {
            $distance = $route[0];
            $duration = $route[1];
            $query = "INSERT INTO droute(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";  //distance in km and duration in mins
            $conn->query($query);
            $route_count++;
        }
        echo "Sumeet!!!Success";


        foreach($routes_array2 as $route2)
        {
            $distance = $route2[0];
            $duration = $route2[1];
            $query = "INSERT INTO wroute(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";  //distance in km and duration in mins
            $conn->query($query);
            $route_count++;
        }
        echo "Sumeet  2 !!!Success";   

        foreach($routes_array3 as $route3)
        {
            $distance = $route3[0];
            $duration = $route3[1];
            $query = "INSERT INTO troute(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";  //distance in km and duration in mins
            $conn->query($query);
            $route_count++;
        }
        echo "Sumeet 3!!!Success";            

    }
        else
        {
        echo "Something went wrong!!! Record couldn't be inserted";
    }


    // insert route count whereever you need to ....

    $conn->close();
}
?>
Comments