Fabio97 Fabio97 - 4 months ago 8
PHP Question

Php/jquery: How to show value of array loaded elements from db with a loop?

I've written the following php code:

$query = mysql_query("SELECT * FROM utenti WHERE username = '$username'");
$query_db = mysql_query("SELECT * FROM utenti");
$i = 0;
$array_user = mysql_fetch_array($query);
$dati = array("str"=>array());
while ($array_db = mysql_fetch_array ($query_db)) {
if ($array_user[country] == $array_db[country]) {
if ($array_user[city] == $array_db[city]) {
if ($array_user[cap] == $array_db[cap]) {
if ($array_user[square] == $array_db[square]) {
$dati["str"]["n".$i] = "Nome ".$array_db[username];
$i++;
}
}
}
}
}

echo json_encode ($dati);


I want to load an array using elements from database during a loop:

$dati["str"]["n".$i] = "Nome ".$array_db[username];


and then to show index and value of this array after an Ajax request:

...
success:function(msg){
if(msg){
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
});
}else{
$("#location").html('Not Available');
}


It doesn't work and I can't find the mistake. Could you help me, please?

Answer

Supposing your code

$.each(msg.str, function(key, value){
    console.log(key + ": " + value);
});

works fine.

Then, your attempt $("#location").html(key + ": " + value); means that everytime contents of #location will be overwritten.

Instead, you can use append():

$.each(msg.str, function(key, value){
    console.log(key + ": " + value);
    $("#location").append(key + ": " + value);
});