Muhammad Umar
Muhammad Umar

Reputation: 11782

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

Upvotes: 0

Views: 1415

Answers (1)

keyboardSmasher
keyboardSmasher

Reputation: 2811

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

?>

Upvotes: 2

Related Questions