Mysql
 sql >> Database >  >> RDS >> Mysql

Recupero di dati con Jquery, AJAX e PHP da un database MySQL

Prima di tutto consiglio vivamente di utilizzare un oggetto JS per la variabile di dati nelle richieste ajax. Questo renderà la tua vita molto più semplice quando avrai molti dati. Ad esempio:

$('h1').click(function() {
            $.ajax({
                type:"POST",
                url: "ajax.php",
                data: { "code": code },
                datatype: "xml",
                success: function() {
                $(xml).find('site').each(function(){
                    //do something
                });
            });
        });

Per quanto riguarda l'ottenimento di informazioni dal server, per prima cosa dovrai creare uno script PHP per estrarre i dati dal db. Se supponi di ottenere molte informazioni dal server, in aggiunta potresti voler serializzare i tuoi dati in XML o JSON (raccomanderei JSON).

Nel tuo esempio, presumo che la tua tabella db sia molto piccola e semplice. Le colonne disponibili sono ID, codice e descrizione. Se vuoi estrarre tutte le descrizioni delle notizie per un codice specifico, il tuo PHP potrebbe assomigliare a questo. (Non faccio PHP da un po', quindi la sintassi potrebbe essere sbagliata)

// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
    private $id = null;
    var $code = null;
    var $description = null;

    function setID($id) {
        $this->id = $id;
    }
    function setCode($code) {
        $this->code = $code;
    }
    function setDescription($desc) {
        $this->description = $desc;
    }
}

// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to

// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));

// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);

// get the data
while ($result = mysql_fetch_assoc($query)) {
    $data = new NewsDB();
    $data.setID($result['id']);
    $data.setCode($result['code']);
    $data.setDescription($result['description']);
    // append data to the array
    array_push($data_array, $data);
}

// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);

L'output di esempio:

[
  { "code": 5, "description": "desc of 5" },
  { "code": 6, "description": "desc of 6" },
  ...
]

Quindi in questa fase avrai uno script PHP che restituisce i dati in JSON. Assumiamo inoltre che l'URL di questo script PHP sia foo.php .

Quindi puoi semplicemente ottenere una risposta dal server tramite:

$('h1').click(function() {
            $.ajax({
                type:"POST",
                url: "foo.php",
                datatype: "json",
                success: function(data, textStatus, xhr) {
                   data = JSON.parse(xhr.responseText);
                   // do something with data
                   for (var i = 0, len = data.length; i < len; i++) {
                       var code = data[i].code;
                       var desc = data[i].description;
                       // do something
                   }
            });
         });

Questo è tutto.