2016-06-15 2 views
0

배열을 생성하고 내 메인 페이지로 다시 보내고 기존 테이블에 추가하기 위해 작성된 코드가 있습니다.`mysqli_fetch_array`를 json 객체와 하나의 문자열로 보내기

아래 코드에서 생성 된 데이터를 JSON 객체 내의 단일 요소로 보낼 수있는 방법이 있다면 그냥 woundering합니다. 예를 들어

:

{"arraydata":"Data Generated From The below Code","another variable":"some other data"}

등등 ...

어떤 제안이?

 $result = mysqli_query($con," SELECT * FROM `BIMTECH_academy_2016_classes` 
       WHERE `Serial`='$serial' ORDER BY `Serial` "); 

    while($row = mysqli_fetch_array($result)) 
    { 
      echo "<tr id='" . $row['Serial'] . "'>"; 
       echo "<td><img src='images/delete-icon.svg' id='classDeleteIcon'/></td>"; 
       echo "<td class='datepicker' id='Date'>" . $row['Date'] . "</td>"; 
       echo "<td class='timepicker' id='From'>" . $row['From'] . "</td>"; 
       echo "<td class='timepicker' id='To'>" . $row['To'] . "</td>"; 
      echo "</tr>"; 
    } 
+1

에 봐 [로 json_encode()] (http://php.net/manual/en/function.json-encode.php) – Marcus

+0

[리틀 바비] (HTTP : //bobby-tables.com/) *** *** [귀하의 스크립트는 SQL 인젝션 공격의 위험이 있습니다.] (http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection -in-php) *** [MySQLi] (http://php.net/manual/en/mysqli.quickstart.)에 대한 [prepared] (http://en.wikipedia.org/wiki/Prepared_statement) 진술에 대해 알아보십시오. prepared-statements.php). 심지어 [이스케이프 문자열] (http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) 안전하지 않습니다! –

+0

'while' 루프 앞에 빈 배열을 선언하십시오. '$ row's, * 다른 변수 *, * 다른 데이터 * 그리고 마지막으로'json_encode()'배열을 계속 추가하십시오. –

답변

0

while 루프 앞에 변수 ($ html)를 선언하십시오. 모든 데이터 (html 및 $ rows 값)를 $ html 변수에 추가/연결합니다. 다른 키와 값을 가진 배열을 만들면 하나의 키에 $ html 변수가 값으로 포함됩니다.

$html = ''; // a variable 
while($row = mysqli_fetch_array($result)) 
{ // concat all data to $html 
    $html.="<tr id='" . $row['Serial'] . "'>"; 
    $html.="<td><img src='images/delete-icon.svg' id='classDeleteIcon'/></td>"; 
    $html.="<td class='datepicker' id='Date'>" . $row['Date'] . "</td>"; 
    $html.="<td class='timepicker' id='From'>" . $row['From'] . "</td>"; 
    $html.="<td class='timepicker' id='To'>" . $row['To'] . "</td>"; 
    $html.="</tr>"; 
} 
$data_array = array(); // declare array 
$data_array['arraydata'] = $html; // assign to array key 
$data_array['otherdata'] = 'otherdata'; // other data to the array 
$json_data = json_encode($data_array, JSON_HEX_QUOT | JSON_HEX_TAG); // encode array with html tags 
echo $json_data; 

출력 :

{"arraydata":" your html data","otherdata":"otherdata"}