我正在尝试通过在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);
答案 0 :(得分:1)
如果您想依赖名为post_title
的网址参数来为您提供标题中包含“草莓”字样的发布结果,您可以使用以下内容修改当前脚本:
$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
如果未在网址中设置post_title
,则不会发生任何变化。如果是,它会修改您正在构造的SQL语句,以包含LIKE
表达式来过滤查询结果,以便仅包括标题包含通过URL传递的内容的那些。有关详细信息,请参阅以下手册条目。