2017-04-23 127 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