Ar. Lie Ar. Lie - 3 years ago 186
MySQL Question

PHP array from Ajax : SQL request format

I am a bit lost with my PHP file.
I want to find an array with all my datas in the database, and send it with ajax to my js file (this part is OK).

Now, i have :

$cnx = new PDO('mysql:host=localhost;dbname=simul','root','');
$cnx->query('SET NAMES utf8');
$cnx->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

$req = $cnx->prepare('Select * from price');
$req-> execute();

$data = $req->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($data);


My JS :

function set_global_var(){
$.ajax({
type: "POST",
url: '/global.php',
async: false,
success: function(rep){console.log(rep);},
});
}


Print_r :

Array
(
[0] => Array
(
[small-bronze] => 5
)

[1] => Array
(
[small-silver] => 10
)
)


And to access it fast, I just want something like :

[small-bronze] => 5
[small-silver] => 10
[small-gold] => 15


Data Base :

item price
small-bronze 5


How can I do this efficiently ? Is PDO::FETCH_KEY_PAIR wrong ?
Thank you in advance !

Answer Source

global.php

$cnx = new PDO('mysql:host=localhost;dbname=simul','root','');
$cnx->query('SET NAMES utf8');
$cnx->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

$req = $cnx->prepare('Select * from price');
$req-> execute();

$data = $req->fetchAll(PDO::FETCH_KEY_PAIR);
echo json_encode($data);

MY JS

function set_global_var(){
    $.ajax({ 
        type: "POST",
        url: '/global.php',
        async: false, // this is not required (in this case)
        dataType:'json',
        success: function(rep){
           console.log(rep);

           //You can access each items of JSON array as below.
           $.each(resp, function(i, val) {
              console.log(val.small-bronze);
           }

        },
    }); 
 }

Following links would be helpful to you to learn more about this. http://api.jquery.com/jquery.ajax/ http://php.net/manual/en/function.json-encode.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download