使用变量Query将SQL转换为XML

时间:2022-10-30 10:04:03

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.

我想从数据库中获取值并将它们放在XML临时文件中(对于Google Maps webapp),然后将它们分配给输入值。

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.

如果查询是静态的,我知道怎么做,比如Select * from markers其中1,但我想做一些像SELECT * from markers WHERE ID = $ id,这个$ id来自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?

我有一个带JS的HTML文件,它调用PHP存档来获取XML并解析它。它适用于静态查询,但如何使这些查询动态化?如何将该变量从JS函数传递给我的PHP文件?

Here's my code to get the XML:

这是获取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:

这里是调用PHP文件并获取XML的JS:

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.

我想做的是像函数downloadUrl(url,callback,id),并通过POST发送ID。

Is this possible or which method I Should use?

这可能或我应该使用哪种方法?

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

非常感谢,抱歉我缺乏好的解释。

1 个解决方案

#1


1  

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

在JavaScript端,您可以为downloadUrl()函数添加第三个参数。并将open命令设置为使用POST而不是GET

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

And to send the id with the request

并发送带有请求的id

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

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

在PHP端捕获并过滤传入的请求变量。并将其添加到查询中。

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

#1


1  

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

在JavaScript端,您可以为downloadUrl()函数添加第三个参数。并将open命令设置为使用POST而不是GET

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

And to send the id with the request

并发送带有请求的id

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

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

在PHP端捕获并过滤传入的请求变量。并将其添加到查询中。

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