2017-04-23 1 views
0

mysql을 쿼리하고 결과를 반환하는 PHP 페이지로 데이터를 보내기 위해 ajax를 사용하고 있습니다. 내 페이지에서 dept 값을 보유하는 변수가 있습니다. 그러나, 만약 내가 var_dump ($ _ POST) var에 배열을 참조하십시오.json 배열을 디코딩하는 방법

수동으로 쿼리에 값을 입력하면 데이터가 반환됩니다. 그러나, 단지 내 $ dept var를 사용하지 마십시오.

내 쿼리에서 변수를 사용할 수있게하려면이 배열을 어떻게 디코딩해야합니까? 감사합니다

아약스 코드

$.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의 주입에 열려있어 : 대신 객체로 반환 전자 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.. 

당신이 두 번째 매개 변수로 true를 전달하지 않는 경우 json_decod http://php.net/manual/en/mysqli.quickstart.prepared- ([문 준비]에 보면,

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

관련 문제