2017-04-13 36 views
-3

我想使用此學生ID號檢索學生參加的所有事件。所以這是我的PHP代碼,這個代碼正在工作,但它只能檢索1個事件,而這個學生已經參加了幾個事件。從JSON數組中檢索所有數據

<?php 
$host='localhost'; 
$username='tan'; 
$password='1234567'; 
$db='feedback01'; 

$conn=mysqli_connect($host,$username,$password,$db); 

if (!$conn) 
    { 
    die('Could not connect: ' . mysqli_connect_error()); 
    } 
    $studentID=$_POST['StudentID']; 

    $studentID=mysqli_real_escape_string($conn,$studentID); 
    $query="SELECT * From PassportData WHERE StudentID='$studentID'"; 
    $result=mysqli_query($conn,$query); 
    $response = array(); 
    if(mysqli_num_rows($result)>0) 
    { 
     $row = mysqli_fetch_assoc($result); 
     $event = $row["Events"]; 
     $date = $row["Date"]; 
     $code = "login_success"; 
     array_push($response, array("code"=>$code, "Events"=>$event, "Date"=>$date)); 
     echo json_encode($response); 
    } 
    else{ 
     $code = "login_failed"; 
     $message = "not found!"; 
     array_push($response, array("code"=>$code, "messsage"=>$message)); 
     echo json_encode($response); 
     } 
    mysqli_close($conn); 
?> 
+0

您應該循環$行= mysqli_fetch_assoc( $結果)該聲明。 –

+0

*這是我的PHP代碼*那麼爲什麼將這個問題標記爲Java? –

回答

0

我不知道你的表結構,但我認爲你必須改變你的代碼是這樣的:?

if(mysqli_num_rows($result)>0) { 
    $response = []; 
    while($row = mysqli_fetch_assoc($result)) { 
    $response[] = $row; 
    } 
    echo json_encode($response); 
} else{ 
    $code = "login_failed"; 
    $message = "not found!"; 
    array_push($response, array("code"=>$code, "messsage"=>$message)); 
    echo json_encode($response); 
} 
mysqli_close($conn); 

>

+0

非常感謝。這真的很有幫助。 –

0

您的代碼應該是。用結果數組嘗試while循環。

if(mysqli_num_rows($result)>0) 
{ 
    while($row = mysqli_fetch_assoc($result)){ 
    $event = $row["Events"]; 
    $date = $row["Date"]; 
    $code = "login_success"; 
    array_push($response, array("code"=>$code, "Events"=>$event, "Date"=>$date)); 
    } 
    echo json_encode($response); 
} 
+0

對不起,我已經在5秒後回答了非常相似的答案:P –

+0

非常感謝。這真的很有幫助。 –