简体   繁体   中英

Can't get specific data from JSON object, PHP

I'm trying to return specific data from JSON by passing parameters in the url, example below.

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

This does absolutely nothing at all, and would appreciate some advice on how to resolve this.... Please see code below.

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

If you want to rely on a URL parameter named post_title to give you back post results that contain the word 'Strawberry' in the title, you can modify your current script with something along these lines:

$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

If post_title is not set in the URL, nothing changes. If it is, it modifies the SQL statement you are constructing to include a LIKE expression to filter results of the query to only include those whose title contains whatever is passed in through the URL. Refer to the following manual entries for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM