2017-07-16 26 views
1
<?php 

$link = mysql_connect('localhost', 'root', 'admin') 
or die('There was a problem connecting to the database.'); 
mysql_select_db('hospitalmaster'); 

$hnum = (int)$_POST["hnum"]; 
$sql = "SELECT d.doctorid, d.doctorname 
     from hospitalmaster.doctor_master d 
      inner join pharmacymaster.pharbill e 
     where e.hnum = '$hnum' 
     and e.presid = d.d_empno 
     group by e.presid"; 

$result = mysql_query($sql); 
$response = array(); 

if (mysql_num_rows($result) > 0) { 
    while ($row = mysql_fetch_assoc($result)) { 
     $response = $row; 
    } 

    echo json_encode(array("Doctor"=>$response)); 
} else { 
    echo ("no DATA"); 
} 
?> 

我上面所示的API,但作爲JSON對象不是JSON數組此API返回我嗎?我想知道如何獲得dotorid的doctorname作爲一個陣列,因爲我有很多的醫生姓名和身份證,我想每名醫生及其相應的ID作爲idividual陣列,現在他們正在返回它們作爲單個對象。由於這是我第一次編寫api,我不知道如何修改代碼。如何獲取數組而不是json對象?

+3

每當你使用一個建議[了'mysql_'(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in -php) 新代碼中的數據庫擴展 ** [發生這種情況](https://media.giphy.com/media/kg9t6wEQKV7u8/giphy.gif)** 它被棄用並且已經使用了多年,曾經在PHP7中。 如果你剛開始學習PHP,花你的精力學習'PDO'或'mysqli'數據庫擴展和準備的語句。 [從這裏開始](http://php.net/manual/en/book.pdo.php) – RiggsFolly

+0

添加到上面的評論,你可以通過'json_decode JSON對象轉換爲數組($ yourjsonobjectvariable,真);' –

+0

謝謝對於有價值的信息,我這樣做的一個項目,因此本質時間....所以有一些參考我瞭解到這種方式......因此我需要知道如何修改代碼... – nithinsampath

回答

3

你每輪循環在寫陣列。

while ($row = mysql_fetch_assoc($result)) { 
    $response[] = $row; 
    //change ^^ 
} 

您應該使用mysqli_或PDO。下面是mysqli_

<?php 

$link = mysqli_connect('localhost', 'root', 'admin','hospitalmaster') 
or die('There was a problem connecting to the database.'); 

$sql = "SELECT d.doctorid, d.doctorname 
     from hospitalmaster.doctor_master d 
      inner join pharmacymaster.pharbill e 
     where e.hnum = ? 
     and e.presid = d.d_empno 
     group by e.presid"; 

$stmt = $link->prepare($sql); 
$stmt->bind_param('i', (int)$_POST["hnum"]); 
$stmt->execute(); 

if ($stmt->num_rows() > 0) { 
    $result = $stmt->get_result(); 
    $response = array(); 

    while ($row = $result->fetch_assoc()) { 
     $response[] = $row; 
    } 

    echo json_encode(array("Doctor"=>$response)); 
} else { 
    echo ("no DATA"); 
} 
?> 
+0

三江源您寶貴的代碼......感激....再次三江源@RiggsFolly – nithinsampath

相關問題