2016-04-19 12 views
0

下記のURLにパラメータを渡してJSONから特定のデータを返そうとしています。JSONオブジェクト(PHP)から特定のデータを取得できません

http://localhost/api/api.php?post_title=Strawbrerry 

これは絶対に何もせず、これを解決する方法についてのアドバイスをいただければ幸いです。下のコードをご覧ください。

$connection = @mysqli_connect($server, $user, $password, $db); 

if(! $connection) die("Error ".mysqli_connect_error()); 

$sql = "SELECT * FROM posts"; 
$result = mysqli_query($connection, $sql); 
$array_post = array(); 

while($data = mysqli_fetch_assoc($result)){ 
$array_post['post_title'][] = $data['post_title']; 
$array_post['post_description'][] = $data['post_description']; 
$array_post['post_image'][] = $data['post_image']; 
$array_post['posted_by]'][] = $data['posted_by']; 
$array_post['[post_date]'][] = $data['post_date']; 
} 
echo json_encode($array_post); 
+0

? api.phpで? –

+0

はい.... api.phpはJSONを表示します。 –

+0

'post_title'が' Strawbrerry'のデータが必要ですか? –

答えて

1

あなたが戻ってタイトルに単語「ストロベリー」を含むポストの結果をお渡しするpost_titleという名前のURLパラメータに依存する場合は、これらの線に沿って何かを使用して、現在のスクリプトを変更することができます。

$sql = "SELECT * FROM posts"; 
if(isset($_GET['post_title']) && $_GET['post_title']) { 
    $sql .= " WHERE post_title LIKE '%?%'"; 
    // Use prepared statements here. Don't trust GET parameters 
    // to not be SQL injection attempts. 
    $stmt = mysqli_prepare($connection, $query); 
    mysqli_stmt_bind_param($stmt, 's', $_GET['post_title']); 
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_bind_result($stmt, $result); 
} else { 
    $result = mysqli_query($connection, $sql); 
} 

// Here, $result should hold the result set 

URLにpost_titleが設定されていない場合は、何も変わりません。存在する場合は、構築中のSQL文にLIKE式を含めるように変更して、クエリーの結果をフィルタリングし、そのタイトルにURLを介して渡されたものが含まれるもののみを含めるようにします。詳細については、以下のマニュアル項目を参照してください。このコードが書かれている

関連する問題