2017-04-24 78 views
1

在我的Android应用程序创建一个JSON数组,如:如何使用Php将我的JSON数组中的对象插入到我的数据库中?

[{"phone_number":"12345678"},{"phone_number":"23456789"},{"phone_number":"34567890"}, etc... etc... 

我的Android代码如下所示:

public static final String KEY_PHONENUMBER = "phonenumber"; 

@Override 
    protected Map<String, String> getParams() throws AuthFailureError { 
     Map<String, String> params = new HashMap<String, String>(); 
    //The KEY, KEY_PHONENUMBER = "phonenumber" . In PHP we will have $_POST["phonenumber"] 
    //The VALUE, phonenumber, will be of the form "12345678" 
     params.put(KEY_PHONENUMBER,jsonArrayContacts.toString()); 
     return params; 
} 

如何我可以插入这些电话号码变成我的用户表?

我知道PHP的插入代码本身线沿线的:

$insert_into_user_command = "INSERT INTO user WHERE username = '$value'"; 
$insert_into_contacts_table = mysqli_query($con,$insert_into_contacts_command); 

但是你能告诉我确切的代码?做一个单独的值很容易,但不知道如何将它们插入到一个POST中。

我知道我是在正确的轨道上为我在Android的反应表明我所有的电话号码在我的JSON阵列具有:

require('dbConnect.php'); 

$json = $_POST['phonenumber']; 
$array = json_decode($json); 
    foreach ($array as $value) 
    { 
     echo $value->phone_number ; 
    } 
+0

** WARNING **:当使用'mysqli'你应该使用[参数化查询](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)和['bind_param'](http://php.net/manual/en/mysqli -stmt.bind-param.php)将用户数据添加到您的查询中。 **不要**使用字符串插值或连接来完成此操作,因为您创建了严重的[SQL注入漏洞](http://bobby-tables.com/)。 **不要**将'$ _POST','$ _GET'或**任何**用户数据直接放入查询中,如果有人试图利用您的错误,这可能会非常有害。 – tadman

+0

@tadman谢谢。此代码仅供个人使用,会在上市时处理安全问题。 – CHarris

+0

这不仅仅是为了安全。这样你就不用花费几个小时来追踪一个愚蠢的,可逃避的漏洞。正确地做。这并不难,它将为您节省大量时间。 – tadman

回答

0
<?php 

require('dbConnect.php'); 
$json = $_POST['phonenumber']; 
$array = json_decode($json); 
    foreach ($array as $value) 
    { 

     $phonenumber = $value->phone_number; 
     $insert_into_user_command = "INSERT INTO user (username) VALUES ('$phonenumber')"; 
     $insert_into_user_table = mysqli_query($con,$insert_into_user_command); 

    } 

?> 
相关问题