Home » Php » PHP:Problems with Creating a Store Locator on Google Maps

PHP:Problems with Creating a Store Locator on Google Maps

Posted by: admin February 25, 2020 Leave a comment

Questions:

Can anyone tell me whats wrong with the code?I am new to php. I followed the instruction on https://developers.google.com/maps/solutions/store-locator/clothing-store-locator but cant get any result when appending ?

lat=-33&lng=151.2&radius=100

I also changed the code in storelocator.

PHP CODE :

<?php
    require("phpsqlsearch_dbinfo.php");

    // Get parameters from URL
    $center_lat = $_GET["lat"];
    $center_lng = $_GET["lng"];
    $radius = $_GET["radius"];

    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

    // Opens a connection to a mySQL server
    $connection=mysqli_connect('localhost','root','');
    if (!$connection) {
        die("Not connected : " . mysql_error());
    }
    // Set the active mySQL database
    $db_selected = mysqli_select_db($connection,'fyp');
    if (!$db_selected) {
        die ("Can\'t use db : " . mysql_error());
    }

    // Search the rows in the markers table
    $query = sprintf("SELECT id, name, address, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
    mysqli_real_escape_string($connection,$center_lat),
    mysqli_real_escape_string($connection,$center_lng),
    mysqli_real_escape_string($connection,$center_lat),
    mysqli_real_escape_string($connection,$radius));
    $result = mysqli_query($connection,$query);
    $result = mysqli_query($connection,$query);
    if (!$result) {
        die("Invalid query: " . mysql_error());
    }

    // Iterate through the rows, adding XML nodes for each
    while ($row = $result->fetch_assoc()){
        $node = $dom->createElement("marker");
        $newnode = $parnode->appendChild($node);
        $newnode->setAttribute("id", $row['id']);
        $newnode->setAttribute("name", $row['name']);
        $newnode->setAttribute("address", $row['address']);
        $newnode->setAttribute("lat", $row['lat']);
        $newnode->setAttribute("lng", $row['lng']);
        $newnode->setAttribute("distance", $row['distance']);
    }
    echo $dom->saveXML();
?>
How to&Answers:

The SQL in your question takes user input directly and is potentially vulnerable to SQL injection despite the use of mysqli_real_escape_string so it would be advisable to use a prepared statement. There are comments throughout the following to give further guidance but this works in testing ( using different db connection of course )

<?php

    /* only proceed if the required querystring parameters are present */
    if( isset( $_GET['lat'], $_GET['lng'], $_GET['radius'] ) ){


        # create db connection ( Object Orientated is less verbose! )
        require 'phpsqlsearch_dbinfo.php';
        $db = new mysqli( 'localhost', 'root', '', 'fyp' );



        # assign querystring parameters as variables
        $lat=floatval( $_GET['lat'] );
        $lng=floatval( $_GET['lng'] );
        $radius=intval( $_GET['radius'] );


        # only proceed if these variables are set
        if( $lat && $lng && $radius ){

            # sql with placeholders
            $sql='select 
                    id, 
                    name, 
                    address, 
                    lat, 
                    lng, 
                    ( 3959 * acos( cos( radians( ? ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( ? ) ) + sin( radians( ? ) ) * sin( radians( lat ) ) ) ) as distance 
                from markers 
                    having distance < ?
                order by distance 
                    limit 0 , 20';

            $stmt=$db->prepare( $sql );
            if( $stmt ){

                # bind the placeholders to the input variables & execute the query
                $stmt->bind_param('sssd', $lat, $lng, $lat, $radius );
                $res=$stmt->execute();

                # if there are results, generate the XML
                if( $res ){

                    $stmt->store_result();
                    $stmt->bind_result( $id, $name, $address, $lat, $lng, $distance );

                    /* create DOMDocument instance and find root or create new root node */
                    $dom=new DOMDocument;
                    $dom->formatOutput=true;
                    $dom->preserveWhitespace=true;
                    $root=$dom->createElement('markers');
                    $dom->appendChild( $root );

                    # process the recordset
                    while( $stmt->fetch() ){
                        $attribs=array(
                            'id'        =>  $id,
                            'name'      =>  $name,
                            'address'   =>  $address,
                            'lat'       =>  $lat,
                            'lng'       =>  $lng,
                            'distance'  =>  $distance
                        );
                        # create new marker node for each record
                        $marker=$dom->createElement('marker');
                        $root->appendChild( $marker );

                        # add the attributes for the marker node
                        foreach( $attribs as $attr => $value ){
                            $marker->setAttribute( $attr, $value );
                        }
                    }
                    $stmt->free_result();
                    $stmt->close();
                    $db->close();


                    # send the results
                    exit( $dom->saveXML() );
                }else{
                    # no results....
                }
            }else{
                exit('Failed to prepare SQL query');
            }
        }else{
            exit('Values for lat,lng or radius seem incorrect');
        }
    }else{
        exit('No latitude, longitude or radius...');
    }
?>