2017-07-16 19 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を持っていますが、このapiはjsonオブジェクトではなくjsonオブジェクトとして返していますか?私は多くの医師の名前とIDを持っているので、私は医師とその対応するidをidividual配列として望んでいるので、今は個々のオブジェクトとして戻っています。以来、これは私の初めてのAPIを書いている、私はコードを変更する方法を知りません。jsonオブジェクトの代わりに配列を取得するには?

+3

あなたが使用するたびのための提案がある[ 'mysql_'](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in -fp) データベース拡張子を新しいコード ** [これが起こります](https://media.giphy.com/media/kg9t6wEQKV7u8/giphy.gif)** これは廃止され、何年も経ていますこれまでPHP7で。 PHPを学んでいるだけなら、 'PDO'や' mysqli'データベースの拡張機能や準備した文を学ぶことができます。 [ここから] – RiggsFolly

+0

上記のコメントを追加すると、jsonオブジェクトを 'json_decode($ yourjsonobjectvariable、true);で配列に変換できます。 –

+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

関連する問題