Saturday, February 13, 2016

PHP SQLite JSON Decode Encode HTTP Response


.

PHP SQLite JSON Decode Encode HTTP Response

In the previous tutorial,http://php-steps.blogspot.my/2016/02/php-and-sqlite-form-validate-submit-and.html  , we use addbuddy.php script to get parameter values from the submitted form and insert the values to the database table.
We will modify the addbuddy.php so that it is able to parse JSON Data and insert these values to the database table. To do this, we will rewrite the script so that it could operate in two modes ie json mode or html mode.

0) Starting Up

1) Write the script logic

We write the script outlines to see the logic.
File: addbuddy.php
<?php
function getDB() {
        //DB connection details
}
if (isset($_POST['submit'])) {
        //if $_POST['jsondata'] exists, set jsonmode=true
        //if jsonmode set variables from json object
        //else set variables from post item
        try {
                //connect to DB
                //execute SQL
                
                   //if jsonmode, returns json format
                   //else return html format
            // close the database connection
        }        
        catch(PDOException $e){
                   //if jsonmode, returns json format
                   //else return html format                
        }
}
?>

2) Write PHP Codes

File: addbuddy.php
<?php
function getDB() {
        $dbConnection = new PDO("sqlite:buddies.sdb");
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $dbConnection;
}
if (isset($_POST['submit'])) {
        //if $_POST['jsondata'] exists, set jsonmode=true
        if (isset($_POST['jsondata'])){
                $jsonmode=true;
        }else{
                $jsonmode=false;                
        }
        //if jsonmode set variables from json object
        //else set variables from post item
        if ($jsonmode){
                $jsondata=$_POST['jsondata'];
                $jsondata=stripslashes(html_entity_decode($jsondata));
                $jsonobject=json_decode($jsondata,true);
                $name= $jsonobject['name'];
                $email= $jsonobject['email'];
                $photo= $jsonobject['photo'];
        } elseif (isset($_POST['name']) &&
                isset($_POST['email']) &&
                        isset($_POST['photo'])){
                                $name=$_POST['name'];
                                $email=$_POST['email'];
                                $photo=$_POST['photo'];
        }
        try {
                //connect to DB
                $DB=getDB();
                //execute SQL
                   $DB->exec("INSERT INTO tblbuddies (name, email, photo)
                                    VALUES ('$name','$email','$photo')");
                
                   //if jsonmode, returns json format
                   //else return html format
                if ($jsonmode){  
                        $response = array();
                        $response["status"] = "success";
            $response["message"] = "Data added successfully";
            http_response_code(200);
            echo json_encode($response);
                    //alternative output
                                //echo '{"200":'.json_encode($response).'}';
                }else{
                    echo "Data added successfully";                                    
                }
            // close the database connection
            $DB = NULL;                                            
                }        
        catch(PDOException $e){
                   //if jsonmode, returns json format
                   //else return html format                
                if ($jsonmode){  
                        $response = array();
                        $response["status"] = "error";
            $response["message"] = $e->getMessage();
            http_response_code(500);
            echo json_encode($response);
                }else{
                    echo 'Exception : '.$e->getMessage();
                }            
        }
}
?>
OUTCOME.
If the user sends jsondata, the script returns json formatted output.
Otherwise, the script returns plain text output.
We are going to test for Error (database not found).
Change the database name to buddies1.sdb
OUTCOME.
We will get an error message saying no such table (because buddies1 does not exist)
Take note that even though in the above example we send both json data and normal form data, our script has been written to give priority to json data and therefore normal form data will not be processed.
.

No comments:

Post a Comment

Labels