简体   繁体   中英

Get JSON String from PDO PHP

I have a table with name location and its rows are latitude , longitude and radius . Since new to php i am confused of how can i make these enteries as json and send it back to server.

This is the current code I am using

function Location()
{
    try 
    {
        $conn = $this->GetDBConnection();

        $statement = $conn->prepare('SELECT * FROM location LIMIT 1');
        $statement->execute();

        if(!($row = $statement->fetch(PDO::FETCH_OBJ)))
        {
            throw new Exception('Connection failed.');
        }

        $conn = null;

        while($row = $statement->fetch(PDO::FETCH_OBJ)) 
        {
            if($row->type == 'longitude') 
            {
              // WHAT TO DO HERE
            }
            if($row->type == 'latitude') 
            {

            }               
            if($row->type == 'radius') 
            {

            }
        }

        return //JSON STRING;
    } catch(PDOException $e) 
    {
        throw $e;
    }
}

You are only fetching one row from the database, so there's no need for a "while" loop. No need to prepare/execute the query either, since it's a static query.

<?php

function Location(){

    $conn = $this->GetDBConnection();
    $statement = $conn->query('SELECT * FROM location LIMIT 1');
    $data = $statement->fetch(PDO::FETCH_ASSOC);

    return json_encode($data);
}

?>

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