<?php
//=============================================================================
// Web Service
//       Receives name:   The country/state/county/city name to search for
//                format: The type of output format desired XML or JSON
//       Returns: data from database as either XML format or JSON format
//                if XML  then XML standard
//                if JSON then array of objects as:
//                        [ 
//                            {"name":"value", "name2":"value2", ...}, 
//                            {"name":"value", "name2":"value2", ...} 
//                        ]  
//=============================================================================

    error_reporting(0);          #turn off PHP error reporting

    $colNames = array();         #array to hold returned column names
    $data     = array();         #2 dim array to hold returned data

//    header("Access-Control-Allow-Origin: *");		#allow access across domains

    read_param();                #read data from the query String
    execute_sql();               #execute the SQL                        
    send_result();               #send the results using either XML or JSON

//=============================================================================
function read_param()
{
    global $searchStr, $format;

    $searchStr = $_GET['name'];               	#get HTML form param fields
    $format    = $_GET['format']; 	 
    
    if (! $format) $format = 'JSON';		    #if not provided use JSON     
}

//=============================================================================
function execute_sql()
{
    global $searchStr, $format, $data, $error;

    if (! $searchStr)
    {
       $error='Enter URL?name=...&format=XML|JSON';
       include "zCode/include.php";
       return;
    }

    $connect = mysqli_connect("p:localhost","demo2","demo2","demo2");   #persistent connection
    if (! $connect)
    {
        $error = 'Could not connect: ' . mysqli_connect_error();
        return;
    }
                                       
    $sql = "select name, type from country  
             where name like '$searchStr%' 
             order by name";    

    $cursor = mysqli_query($connect, $sql);      #execute the query
    if (! $cursor)
    {
        $error = 'Could not execute query: ' . mysqli_error($connect);
        return;
    }

    $i=0;
    while ($row = mysqli_fetch_row($cursor))      #loop thru rows
        $data[$i++] = $row;                       #store row in 2 dim data array

    mysqli_free_result($cursor);                  #free result buffer

}

//=============================================================================
function send_result()
{
    global $data, $searchStr, $format, $error;

    //------if no parameters were entered------------------------------------

    if (! $searchStr)
    {
        header("Access-Control-Allow-Origin: *");		#allow access across domains
        header("Content-type: text/html");
        
        print "<h3> $error </h3> \n";

        include "include.php";

        return;
     }

     //------for XML-----------------------------------------------------------

    if ($format=='XML' || $format=='xml')               #if requesting XML 
    {
        header("Access-Control-Allow-Origin: *");		#allow access across domains
        header("Content-type: text/xml");
        
        print "<?xml version='1.0'?> \n";

        print "<sqlData> \n";

        foreach($data as $row)                          #loop thru the rows
        {
            $name = $row[0];				            #first column			
            $type = $row[1];				            #second column			

            print "    <row> \n";
            print "        <name>$name</name> \n";
            print "        <type>$type</type> \n";
            print "    </row> \n";
        }

        if ($error)
            print "<error> $error </error> \n";

        print "</sqlData> \n";
     }

    //-----For JSON-----------------------------------------------------------

    if ($format=='JSON' || $format=='json')             #if requesting JSON 
    {
        header("Access-Control-Allow-Origin: *");		#allow access across domains
        header("Content-type: text/plain");
                
        $jsonString =  "[ \n";

        foreach($data as $row)                          #loop thru the rows
        {
            $name = $row[0];				            #first column			
            $type = $row[1];				            #second column			

            $jsonString .= "    {";
            $jsonString .= "\"name\":\"$name\", ";
            $jsonString .= "\"type\":\"$type\"";

            $jsonString .= "}, \n";
        }
        $jsonString = preg_replace("/, \n$/"," \n", $jsonString);   #strip off the last comma for the array 

        $jsonString .=  "] \n";


//        $arrObj = array();                                       #create an array
//        foreach($data as $row)                                   #loop thru the rows
//        {
//            $arrObj[] = ["name"=>$name, "type"=>$type];          #create a keyed array, and append to $arrObj
//        }
//        $jsonString  = json_encode($arrObj);                     #convert PHP array of object to JSON



        if ($error)
            print "[ {\"error\":\"$error\"} ] \n";
        else 
            print $jsonString;
     }}

//=============================================================================
?>