可以';t从JSON对象PHP中获取特定数据


Can't get specific data from JSON object, PHP

我正试图通过在url中传递参数来从JSON返回特定数据,示例如下。

 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);

如果您想依靠名为post_title的URL参数来返回标题中包含单词"Strawberry"的发布结果,您可以使用以下行修改当前脚本:

$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传入的内容的结果。有关更多信息,请参阅以下手册条目。

  • mysqli_prepare
  • mysqli_stmt_bind_param
  • mysqli_stmt_execute
  • mysqli_stmt_bind_result