2014-06-13 61 views
0
<?php 
include"../database_conn.php"; 
$con=mysqli_connect("localhost","admin","123456","ayurveadic"); 

$query_pag_data = "SELECT id from diseases"; 
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); 

while ($row = mysql_fetch_array($result_pag_data)) { 
    $diseases_id = $row['id']; 

    $result = mysqli_query($con,"SELECT $diseases_id FROM treatment WHERE gender_id = '10' AND diseases_id = '$diseases_id'"); 
    $row_gid = mysqli_fetch_array($result); 
    if ($row_gid == TRUE){ 

     $sl_dise = mysqli_query($con,"SELECT Diseases_type, id FROM diseases WHERE id = '$diseases_id'"); 

     $rowss = array(); 
     while($r = mysqli_fetch_assoc($sl_dise)) { 
      $rowss[] = $r; 
     } 
     print json_encode($rowss); 
    } 
} 

輸出是:多的mysqli選擇

[{"Diseases_type":"fever","id":"114"}][{"Diseases_type":"rhrh","id":"123"}] 

我怎樣才能得到這樣的輸出:

[{"Diseases_type":"fever","id":"114"},{"Diseases_type":"rhrh","id":"123"}] 
+0

爲什麼你要混合** mysql _ **和** mysqli _ **。總是首選** mysqli _ **,因爲** mysql _ **已被棄用。 – Ranjith

+0

[PHP將數組合併成一個大數組]可能重複(http://stackoverflow.com/questions/10034521/php-combine-arrays-into-one-big-array) –

回答

2

需要初始化外循環前的JSON數組,並打印出來在最後,不是每一次。

<?php 
include"../database_conn.php"; 
$con=mysqli_connect("localhost","admin","123456","ayurveadic"); 

$query_pag_data = "SELECT id from diseases"; 
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); 

$rowss = array(); 
while ($row = mysql_fetch_array($result_pag_data)) { 
    $diseases_id = $row['id']; 

    $result = mysqli_query($con,"SELECT $diseases_id FROM treatment WHERE gender_id = '10' AND diseases_id = '$diseases_id'"); 
    $row_gid = mysqli_fetch_array($result); 
    if ($row_gid == TRUE){ 

     $sl_dise = mysqli_query($con,"SELECT Diseases_type, id FROM diseases WHERE id = '$diseases_id'"); 

     while($r = mysqli_fetch_assoc($sl_dise)) { 
      $rowss[] = $r; 
     } 
    } 
} 
print json_encode($rowss); 
+0

非常感謝Barmar。 – yathavan

0

把你結束的這個while ($row = mysql_fetch_array($result_pag_data)) {

print json_encode($rowss); 

後還要去掉這個$rowss = array();數組初始化

+1

這不是他需要改變的全部,因爲他每次循環都重新初始化'$ rowss'。 – Barmar

+0

感謝指出。 – Ranjith

+0

爲什麼downvoted?你能指出我的錯誤嗎? – Ranjith

1

這裏是你優化的代碼

<?php 
include"../database_conn.php"; 
$con=mysqli_connect("localhost","admin","123456","ayurveadic"); 

$query_pag_data = "select diseases.Diseases_type,diseases.id from diseases inner join treatment on treatment.diseases_id = diseases.id where treatment.gender_id = '10' "; 
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); 

$rowss = array(); 
while ($row = mysqli_fetch_assoc($result_pag_data)) { 
    $rowss[] = $row; 
} 
print json_encode($rowss); 
?> 
+3

你爲什麼用SELECT *替換'SELECT Diseases_type,id'?我們應該鼓勵人們選擇特定的專欄。 – Barmar

+0

@Barmar好的。同意和更新的代碼。但爲什麼要投票? – Anish

+0

我沒有downvote。我最初選擇了,然後解開它直到你解決這個問題。 – Barmar