2012-10-20 15 views
1

我想從我的數據庫檢索JSON數據並解析它們在表中。MySQL + JSON:檢索所有數據,其中id = term

目前我找回它是這樣的:

xmlhttp = new XMLHttpRequest() 

xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     var jsontext = xmlhttp.responseText; 
     var json = JSON.parse(jsontext); 

     console.log(json.service) 

    } 
} 

xmlhttp.open("GET", "mysql.php?p=getservice" + "&carid=" + "KYF111", true); 
xmlhttp.send(); 

這將會給我一個結果,不管我有多少行與ID爲「術語」。

我mysql.php文件看起來像這樣:

case 'getservice': 

$q = mysql_real_escape_string($_GET['q']); 
$carid = stripslashes($_GET['carid']); 
$query = "SELECT * FROM Service WHERE carid = '".$carid."'"; 

$result = mysql_query($query); 

$json = array(); 
while ($row = mysql_fetch_array($result)) { 

    $json['carid'] = $row['carid']; 
    $json['service'] = $row['service']; 
    $json['date'] = $row['date']; 
    $json['nextdate'] = $row['nextdate']; 
    $json['kilometers'] = $row['kilometers']; 
    $json['servicedby'] = $row['servicedby']; 
    $json['invoice'] = $row['invoice']; 
    $json['cost'] = $row['cost']; 
    $json['remarks'] = $row['remarks']; 

} 
print json_encode($json); 

mysql_close(); 

break; 

這是我的數據庫看起來像:

enter image description here

所以術語將是CardId中,我想所有來自含有carid這一術語的行的值。然後,單個行上的每個值都在a之間。是這樣的:

<tbody> 
    <tr> 
     <td>Tyre</td> 
     <td>10-10-2012</td> 
     <td>31-10-2012</td> 
     <td></td> 
     <td>George</td> 
     <td>8951235</td> 
     <td>0</td> 
     <td>Lorem Ipsum</td> 
    </tr> 
    <tr> 
     <td>Lights</td> 
     <td>17-10-2012</td> 
     <td>23-10-2012</td> 
     <td></td> 
     <td>Antony</td> 
     <td>4367234</td> 
     <td>0</td> 
     <td>Lorem Ipsum</td> 
    </tr> 
</tbody> 

回答

1

嘗試這樣的:

$temp=0; 
    $json = array(); 
     while ($row = mysql_fetch_array($result)) { 

      $json[$temp]['carid'] = $row['carid']; 
      $json[$temp]['service'] = $row['service']; 
      $json[$temp]['date'] = $row['date']; 
      $json[$temp]['nextdate'] = $row['nextdate']; 
      $json[$temp]['kilometers'] = $row['kilometers']; 
      $json[$temp]['servicedby'] = $row['servicedby']; 
      $json[$temp]['invoice'] = $row['invoice']; 
      $json[$temp]['cost'] = $row['cost']; 
      $json[$temp]['remarks'] = $row['remarks']; 
    $temp++; 
     } 
print json_encode($json); 
+0

我沒有得到任何結果。林不知道我做錯了什麼。檢索數據的方式是否正確? – jQuerybeast

+0

你有什麼錯誤? –

+0

沒有錯誤,只是沒有結果,不幸的是 – jQuerybeast

1

while循環每次通過重寫而不是使一個二維陣列在相同的陣列條目。它應該是:

$json = array(); 
while ($row = mysql_fetch_array($result)) { 
    $json[] = $row; 
} 
echo json_encode($json); 

在您的JavaScript中,您需要遍歷返回的數組。取而代之的console.log(json.service)它應該是:

for (var i = 0; i < json.length; i++) { 
    console.log(json[i].service); 
} 
+0

我仍然只得到一個價值,這是燈 – jQuerybeast

+1

你的JavaScript有循環數組過來,看到我的編輯答案。我很驚訝你有任何登錄到控制檯。 – Barmar

+0

是否必須打印或回顯json_encode? – jQuerybeast