简体   繁体   中英

Turning SQL into XML with variable Query

I want to get values from a database and put them in an XML temp file (for a Google Maps webapp) and then assign them to an input value.

I know how to do it if the query is static, like Select * from markers where 1 but I want to do something like Select * from markers WHERE ID = $id , and this $id is from a POST.

I have an HTML file with JS that calls a PHP archive to get XML and parse it. It works with static queries, but how can I make those queries dynamic? How can I pass that variable from the JS function to my PHP file?

Here's my code to get the XML:

<?php
    $username="SOMEUSER";
    $password="SOMEPASSS";
    $database="SOMEUSER_marcadoresMapas";

    function parseToXML($htmlStr) 
    { 
        $xmlStr=str_replace('<','&lt;',$htmlStr); 
        $xmlStr=str_replace('>','&gt;',$xmlStr); 
        $xmlStr=str_replace('"','&quot;',$xmlStr); 
        $xmlStr=str_replace("'",'&apos;',$xmlStr); 
        $xmlStr=str_replace("&",'&amp;',$xmlStr); 
        return $xmlStr; 
    } 

    // Opens a connection to a mySQL server
    $connection=mysql_connect (localhost, $username, $password);
    if (!$connection) {
        die('Not connected : ' . mysql_error());
    }

    // Set the active mySQL database
    $db_selected = mysql_select_db($database, $connection);
    if (!$db_selected) {
        die ('Can\'t use db : ' . mysql_error());
    }

    // Select all the rows in the markers table
    $query = "SELECT * FROM markers WHERE clave";
    $result = mysql_query($query);
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }

    header("Content-type: text/xml");

    // Start XML file, echo parent node
    echo '<markers>';

    // Iterate through the rows, printing XML nodes for each
    while ($row = @mysql_fetch_assoc($result)){
        // ADD TO XML DOCUMENT NODE
        echo '<marker ';
        echo 'name="' . parseToXML($row['name']) . '" ';
        echo 'address="' . parseToXML($row['address']) . '" ';
        echo 'lat="' . $row['lat'] . '" ';
        echo 'lng="' . $row['lng'] . '" ';
        echo 'telefono="' . $row['telefono'] . '" ';
        echo 'zona="' . $row['zona'] . '" ';
        echo 'ciudad="' . $row['ciudad'] . '" ';
        echo 'email="' . $row['email'] . '" ';
        echo 'piso="' . $row['piso'] . '" ';
        echo 'tipo="' . $row['tipo'] . '" ';
        echo 'erasmus="' . $row['erasmus'] . '" ';
        echo 'nhabitaciones="' . $row['nhabitaciones'] . '" ';
        echo 'plazas="' . $row['plazas'] . '" ';
        echo 'equipHabita="' . $row['equipHabita'] . '" ';
        echo 'nbanos="' . $row['nbanos'] . '" ';
        echo 'salon="' . $row['salon'] . '" ';
        echo 'cocina="' . $row['cocina'] . '" ';
        echo 'electrodomesticos="' . $row['electrodomesticos'] . '" ';
        echo 'garaje="' . $row['garaje'] . '" ';
        echo 'internet="' . $row['internet'] . '" ';
        echo 'calefaccion="' . $row['calefaccion'] . '" ';
        echo 'sexo="' . $row['sexo'] . '" ';
        echo 'precio="' . $row['precio'] . '" ';
        echo 'superficie="' . $row['superficie'] . '" ';
        echo 'fecha="' . $row['fecha'] . '" ';
        echo 'otros="' . $row['otros'] . '" ';
        echo 'id="' . $row['id'] . '" ';
        echo '/>';
    }

    //echo 'name="' . parseToXML('&','&amp;', $row['name']) . '" ';

    // End XML file
    echo '</markers>';
?>

And here is the JS that calls the PHP file and gets the XML:

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest; //en cierto modo es una API, acepta requests HTTP.

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

 downloadUrl("phpsqlajax_genxml2.php", function(data) {
    var xml = parseXml(data); 
    var markers = xml.documentElement.getElementsByTagName("marker"); //coge todos los markers
    for (var i = 0; i < markers.length; i++) { //coge los atributos de los markers
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var telefono= markers[i].getAttribute("telefono");
      var precio=markers[i].getAttribute("precio");
      //var type = markers[i].getAttribute("type");
      var point = new google.maps.LatLng( //crea LatLng a partir de Lat Long de los markers
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "Nombre:" + name + "<br>Direccion:" + address+"<br>Telefono:"+telefono+"<br>Precio:"+precio;
      var marker = new google.maps.Marker({ //posiciona los markers
        map: map,
        position: point
      });
      bindInfoWindow(marker, map, infoWindow, html); //pone la ventana de información
    }
  });
}

What I want to do is something like function downloadUrl(url, callback,id) and send the ID via POST.

Is this possible or which method I Should use?

Thank you very much, sorry for my lack of good explanation.

On the JavaScript side you can add the third parameter for the downloadUrl() function. And set the open command to use POST instead of GET

request.open('POST', url, true);

And to send the id with the request

var params = 'id='+id;
request.send(params);

On the PHP side catch and filter the incoming request variable. And add it to the query.

$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
$query = "SELECT * FROM markers WHERE id = {$id}";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM