2017-12-08 2 views
-1

のプロパティを取得しようとするにあたっては、私がVaRのダンプを行うと、すべての正しい値が表示され</p> <p> JSONやPHPを使用して、特定のIDのデータベースからの値を表示しようとすると、非オブジェクトエラー

function getItemByID($id) { 

    //Connect to database and server 
    include ("connect.php") ; 

    if (!$connect) { 
    die("Connection failed: " . mysqli_connect_error()); 
    } 

    $sql = "SELECT * FROM items WHERE id ='".$id."'"; 
    $res1 = mysqli_query($connect, $sql); 

    $rows = mysqli_fetch_assoc($res1); 

    $itemtxt = '[{"id" : '.$rows['id'].',' ; 
    $itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ; 
    $itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ; 
    $itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ; 


    $itemtxt = substr($itemtxt, 0, -2) ; 

    var_dump($itemtxt); 

    return $itemtxt; 

} 
エラーがライン上から表示されます

これがどこにある10,11,12,13

<?php 
    $id = $_GET['id']; 

    include("library.php"); 

    $itemtxt = getItemByID($id); 
    $itemjson = json_decode($itemtxt); 


    echo $itemjson -> id; 
    echo $itemjson -> item; 
    echo $itemjson -> image; 
    echo $itemjson -> descr; 

?> 

このデータをこのページに表示しようとしていますが、「非オブジェクトのプロパティを取得しようとしています」というエラーが表示されます。

+0

を、あなたは何をすべきか、出力だから、以下の変更'var_dump($ itemtxt);から取得しますか? –

+1

私はこれを手に入れましょう...あなたがエンコードしている 'getItemByID'では**(手で!)**、後でデコードできますか?手btwでエンコードせず、 'json_decode'に' json_encode'という名前の小さな姉妹がいます。もっと良いことに、 '$ rows'変数を返すだけで、エンコード/デコードをスキップします – YvesLeBorg

答えて

0

作成する文字列はJSON配列です。あなたのjson_decodeが配列を返しています。 を文字列生成の最初と最後から削除してください。私は最初からオブジェクトをフェッチします

$itemtxt = '{"id" : '.$rows['id'].',' ; 
$itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ; 
$itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ; 
$itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'} ,' ; 
0

$itemtxt = '[{"id" : '.$rows['id'].',' ; 
$itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ; 
$itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ; 
$itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ; 

function getItemByID($id,$connect) 
{ 
    if(!$connect) 
     return false; 
    elseif(!is_numeric($id)) 
     return false; 

    $query = mysqli_query($connect, "SELECT * FROM items WHERE id ='{$id}'"); 
    return mysqli_fetch_object($query); 
} 

を使用するには:

# Add connection 
include("connect.php"); 
# You should have this bit right on the connect.php so you don't have to 
# keep writing it on each page you use the connection 
if (!$connect) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 
# Make a check to make sure value is set and is numeric 
$id = (isset($_GET['id']) && is_numeric($_GET['id']))? $_GET['id'] : false; 
# I would include this at the top if it doesn't require $id, it would be cleaner 
include("library.php"); 
# Feed in the connection and ID 
$itemtxt = getItemByID($id,$connect); 
# Check that it's filled and not empty 
if(!empty($itemtxt)) { 
    echo $itemtxt->id; 
    echo $itemtxt->item; 
    echo $itemtxt->image; 
    echo $itemtxt->descr; 
} 
関連する問題