2017-04-24 83 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); 

    } 

?> 
相關問題