用PHP解析Json时遇到问题

时间:2012-04-02 06:42:05

标签: php mysql json

我有一个Android应用程序,它将json字符串发送到我的服务器,其格式如下:

{"drink_name":"testing","phone_number":"5555555555"}

当我使用命令:SELECT * FROM orders时,它显示空白条目已插入表中。

我认为我的问题来自我的PHP脚本(主要是因为我是PHP新手)。 我正确地解析了json吗? 下面是我写的脚本。

<?php 
$handle = mysql_connect('localhost',USERNAME,PASSWORD); 
if($handle==false) 
{ 
die('No database connection'); 
} 

$db=mysql_select_db('r2bar2');


$json = file_get_contents('php://input');
$obj = json_decode($json);


mysql_query("INSERT INTO orders (phone_number, drink_name) 
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
mysql_close($handle);
?>

编辑: 如果有任何帮助,这是我的Android代码。

protected void sendJson(final String phnNmbr, final String drink) {
    Thread t = new Thread(){
        public void run() {
            Looper.prepare(); //For Preparing Message Pool for the child Thread
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
            HttpResponse response;
            JSONObject json = new JSONObject();
            try{
                HttpPost post = new HttpPost("http://kubie.dyndns-home.com/R2Bar2/sendOrder.php");
                json.put("phone_number", phnNmbr);
                json.put("drink_name", drink);
                StringEntity se = new StringEntity( "orders: " + json.toString());  
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                /*Checking response */
                Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
                if(response!=null){
                    InputStream in = response.getEntity().getContent(); //Get the data in the entity
                }
            }
            catch(Exception e){
                e.printStackTrace();
                //createDialog("Error", "Cannot Estabilish Connection");
            }
            Looper.loop(); //Loop in the message queue
        }
    };
    t.start();      
}

3 个答案:

答案 0 :(得分:1)

除了您尝试访问服务器上的json数据之外,我使用了相同的方法。

我曾使用$ _POST数组来访问它,它对我来说效果很好。尝试使用,

$json = $_POST['orders'];
$obj = json_decode($json);

这对我来说非常有效。祝一切顺利 :) (我不认为$ handle存在问题,因为正在将某些内容插入表中)

答案 1 :(得分:1)

我弄清楚我做错了什么。好像我传入的是原始数据类型。为了解析字符串,我使用了以下内容:

$obj = json_decode(file_get_contents("php://input"));

mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");

感谢大家的建议。

答案 2 :(得分:0)

您已按如下方式连接到数据库,您错过了$ handle来建立连接

$handle = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$handle) {
    die('Not connected : ' . mysql_error());
}

// make r2bar2 the current db
$db=mysql_select_db('r2bar2',$handle);
if (!$db) {
    die ('Can\'t use r2bar2 : ' . mysql_error());
}
相关问题