2017-04-23 49 views
0

我正在使用ajax將數據發送到查詢mysql並返回結果的php頁面。我在我的頁面中有一個保存部門值的變量。但是,如果我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

你開到MySQL注入,看看[預處理語句(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.. 

如果您沒有通過真正的第二個參數json_decod Ë將改爲返回它作爲一個對象:

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

'$ data'是什麼? – charlietfl

+0

json數據.. !! $ data = json_decode($ json,true); echo $ data [0] [「name」]; //「Rishii」 $ data = json_decode($ json); echo $ data [0] - > name; //「Rishii」 –

+0

但是在請求有效載荷中沒有顯示問題 – charlietfl