2016-04-25 13 views
-2

データベースからデータを抽出してJsonデータに変換しようとしています。データベースからデータを抽出してJsonデータに変換できません

商品のID、画像、名前、価格の表があります。私はこれらのデータをJsonに変換し、それらを私のウェブサイトに抽出したいと思います。

<?php 
//config is the file where i used to connect php to db 

include_once('config.php'); 

// images is my table name 
$sql= "SELECT * FROM `images` "; 

$res= mysql_query($sql); 

$result = array(); 

while ($row = mysql_fetch_array($res)) 

//image is stored as longbob, name as varchar and price as int 

array_push($result, array('id'=> $row[0], 
          'image' = > $row[1], 
          'name'=> $row[2], 
          'price'=> $row[3] 
)) 




echo json_encode(array()); 




?> 
+0

問題点は何ですか? echo json_encode($ result)のように$ resultをjson_encodeの中に入れます。 –

答えて

0

array_pushは必要ありません。ちょうど配列を続け、このようにしてください:

<?php 
//config is the file where i used to connect php to db 

include_once('config.php'); 

// images is my table name 
$sql= "SELECT * FROM `images` "; 

$res= mysql_query($sql); 
$result=array(); 
while (($row = mysql_fetch_array($res))!==false) 
{ 
    //image is stored as longbob, name as varchar and price as int 
    $result[] = array('id'=> $row[0], 
         'image' = > $row[1], 
         'name'=> $row[2], 
         'price'=> $row[3], 
         'error'=>false, 
         'error_message'=>'' 
       )); 

} 

if(count($result)>0) 
    echo json_encode($result); 
else 
    echo json_encode(array(array('error'=>true,'error_message'=>'No Images'))); 
?> 

私はあなたがAJAXの権利でこれをしたいと思いますか? ajaxで使用する場合は、コードの最後の行にexit;と入力してください。

また、エラーオブジェクトを追加してコードをデバッグするか、データが存在するかどうかを確認することができます。

0

さて、あなたは$result、ないarray()をエンコードする必要がクエリ

$result = array(); 
while ($row = mysql_fetch_array($res)) 
{ 
    //image is stored as longbob, name as varchar and price as int 
    $result[] = array('id'=> $row[0], 
         'image' = > $row[1], 
         'name'=> $row[2], 
         'price'=> $row[3] 
       )); 

} 
echo json_encode($result); 

を実行した後にこれを試してみてください。

関連する問題