2014-02-21 3 views
0

새 프로젝트를 시작한 후 deprecated mysql_query 명령에서 새로운 mysqli 유형 인수로 이동하는 문제가 발생했습니다.유효하지 않은 json_encode 출력

{"id":"3","inGameName":"Syrinathos","friendCode":"0000 0000 0000","safariType":"Normal","safariSlot1":"Aipom","safariSlot2":"Kecleon","safariSlot3":""} 
{"id":"2","inGameName":"Herschel","friendCode":"1234 12341 234","safariType":"Zombie","safariSlot1":"Crawler","safariSlot2":"Runner","safariSlot3":""} 
{"id":"4","inGameName":"Syrinathos","friendCode":"0000 0000 0000","safariType":"Normal","safariSlot1":"Aipom","safariSlot2":"Kecleon","safariSlot3":"Ditto"} 
{"id":"6","inGameName":"Kira","friendCode":"2345 2345 2345","safariType":"Ghost","safariSlot1":"Shuppet","safariSlot2":"Haunter","safariSlot3":"Gengar"} 

이 유효 JSON으로 실종 유일한 요소는 대괄호과 실제 사이의 쉼표는 다음과 같습니다

<?php 

$mysqli = new mysqli("hostname", "username", "password", "dbname"); 

// Check the connection 

if (mysqli_connect_errno()) { 
    printf("Connect failed."); 
    exit(); 
} 

$sql = $mysqli->query("SELECT * FROM SafariFinder_Directory"); 

while ($rows = $sql->fetch_assoc()) { 
    echo json_encode($rows); 
} 

echo $res; 

$mysqli->close(); 

?> 

이 나에게 다음과 같은 출력을 얻을 다음과 같이

코드는 항목. 어떤 도움이라도 대단히 감사하겠습니다.

+1

왜 대괄호가없고 전체적으로 잘못된 json인지는 분명해야합니다. 사이에 아무 것도없는 일련의 json을 연속적으로 덤프 할 수없고 전체적으로 유효한 json을 얻을 수 없습니다. – AD7six

답변

4

결과를 배열에 넣은 다음 배열을 인코딩해야합니다.

$rows = array(); 
while ($row = $sql->fetch_assoc()) { 
    $rows[] = $row; 
} 

echo json_encode($rows); 
+0

그리고 그것은 내가 알기로하고 사랑하는 간단한 수정의 종류입니다. –