2017-04-23 11 views
0

私はajaxを使ってmysqlに問い合わせを行い、結果を返すPHPページにデータを送ります。私は自分のページにdept値を保持する変数を持っています。しかし、私はvar_dump($ _ POST)私はvarが配列であることがわかります。json配列を解読するにはどうすればいいですか?

クエリに手動で値を入力すると、データが返されます。しかし、私の$ dept varを使っていないだけです。

この配列をデコードして、自分のクエリで変数を使用できるようにするにはどうすればよいですか?おかげ

Ajaxコード

$.ajax({ 
    url: 'deptdata.php', 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    data: {dept: depts}, 
    dataType: "json", 
     success: function (data) { 
     console.log(data); 

    }, 
     error: function (data) { 

     alert('error'); 

     } 
     }); 

放火犯タブでポスト

dept=DEMOBILL 

deptdata.php

<?php 

    $dept = $_POST['dept']; <--- array? 
    //open connection to mysql db 
    $connection = mysqli_connect("localhost","root","","sample") or die("Error " . mysqli_error($connection)); 

    //fetch table rows from mysql db 
    $sql = "select custref from boxes where department = '".$dept."' and status = 1"; 
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection)); 

    //create an array 
    $emparray = array(); 
    while($row = mysqli_fetch_assoc($result)) 
    { 
     $emparray[] = $row; 
    } 
    echo json_encode($emparray); 

    //close the db connection 
    mysqli_close($connection); 
?> 
+0

、[プリペアドステートメント](http://php.net/manual/en/mysqli.quickstart.prepared-に見て:それは代わりに、それをオブジェクトとして返します電子statements.php)。 – Nytrix

+0

あなたはjsonを送信しているようではないので、必要はありません。なぜそれのために 'contentType'を設定するのか不明です。 'depts'がどのように定義されているかを表示 – charlietfl

+0

ローカルでしかないので、ライブに行くまで秘密の必要はありません。 – user1532468

答えて

1
$myArray = json_decode($data, true); 

echo $myArray[0]['id']; // Fetches the first ID 
echo $myArray[0]['c_name']; // Fetches the first c_name 
// ... 
echo $myArray[2]['id']; // Fetches the third ID 
// etc.. 

あなたは2番目のパラメータとしてtrueを渡していない場合json_decodあなたはMySQLの注入に開放している

echo $myArray[0]->id; 
+0

'$ data'とは何ですか? – charlietfl

+0

json data .. !! $ data = json_decode($ json、true); echo $ data [0] ["name"]; // "Rishii" $ data = json_decode($ json); echo $ data [0] - > name; // "Rishii" –

+0

しかし、質問 – charlietfl

関連する問題