dimanche 21 février 2016

Converting string to json object or array in php

I have to make a web service. Therefore I referred some tutorials in the internet and came up with the following codes

index.php

<html>
<head>
    <title>Form page</title>
</head>

<body>

    <form action="http://localhost:81/my%20web%20service/webservice" method="get">
        Table name:<br>
        <input type="text" name="s" value=""><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

webservice.php

<?php

    include('connectdb.php');

    $something = $_GET['s'];
    $sqlcode = mysql_query("Select * from $something");

    $jsonObj= array();
    while($result=mysql_fetch_object($sqlcode))
    {
        $jsonObj[] = $result;
    }

    $final_res =json_encode($jsonObj) ;
    echo $final_res;
?>

connectdb.php

<?php
    $hostname="localhost";
    $username="root"; //write your username
    $password=""; //write your password
    $db_name="webservice_trial"; //write your db name
    $con=mysql_connect($hostname,$username,$password);
    mysql_select_db($db_name,$con) or die ("Cannot connect the Database");
    mysql_query("SET NAMES 'utf8'",$con); 

?>

The above codes works fine. When I enter a name of a table from form.php, it will retrieve all tuples in that particular table.

Now what I want to do is to make data display on another page. i.e. I want to transfer data from webservice.php to another page from json format. so I edited my webservice.php as following

webservice.php

<?php

    include('connectdb.php');

    $something = $_GET['s'];
    $sqlcode = mysql_query("Select * from $something");

    $jsonObj= array();
    while($result=mysql_fetch_object($sqlcode))
    {
        $jsonObj[] = $result;
    }

    $final_res =json_encode($jsonObj) ;
    echo $final_res;

    $jsonArray = (array) json_decode($final_res);
    echo jsonArray[0];

?>

it gives the following error

Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\xampp\htdocs\json_folder\my web service\webservice.php on line 18




Aucun commentaire:

Enregistrer un commentaire