2017-07-17 120 views
1

我有一個javascript來創建json數組,它有一個ajax post方法,我必須知道這個json數組應該如何解碼在PHP端?檢索json數組從php json decode

我的JavaScript函數:

var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"datee" : "2017-09-09" ,"total" : tot }], invoiceLine: []}; 

    for(i=1; i<=count+arr.length-1; i++){ 

     var ss = String(i); 
     if(arr.includes(ss)){ 
      continue; 
     } 
     invoices.invoiceLine.push({ 

      "itemName" : document.getElementById('item'+i).value , 
      "qty" : document.getElementById('inputQty'+i).value , 
      "value" : document.getElementById('value'+i).value 
     }); 
    } 

    $.ajax({ 
    type: "POST", 
    url: "saveInvoice.php", 
    data: {json : JSON.stringify(invoices)}, 
    cache: false, 
    success: function(data) { 
    alert(data); 
    location.reload(); 
    } 
    }); 

,這是我的PHP:。(它不會將數據保存到數據庫中,我想先發票數據庫中的數據保存現在然後我可以使用invoiveLine數據。另一個表中插入)

$dbhost = "localhost"; 
    $dbuser = "root"; 
    //$dbpass = "dbpassword"; 
    $dbname = "inventory"; 

    $jsonInvoice = json_decode($POST['invoices'],true); 

    $customerName = $jsonInvoice.["invoice"][0].["customerName"]; 
    $reciptionName = $jsonInvoice.["invoice"][0].["reciptionName"]; 
    $date = $jsonInvoice.["invoice"][0].["datee"]; 
    $total = $jsonInvoice.["invoice"][0].["total"]; 



    mysql_connect($dbhost, $dbuser, ''); 

    mysql_select_db($dbname) or die(mysql_error()); 

    $query = "insert into invoice (customerName,reciptionName,date,total) values ('$customerName','$reciptionName','$date',$total)"; 

    $qry_result = mysql_query($query) or die(mysql_error()); 

    $insertId = mysql_insert_id(); 

    echo $insertId; 
+0

是什麼'$ POST [「發票」]'是什麼樣子?另外,'mysql_'構造函數是[**從PHP 5.5開始不推薦使用](https://wiki.php.net/rfc/mysql_deprecation),並且徹底[**在PHP 7 **中被移除](https ://wiki.php.net/rfc/remove_deprecated_functionality_in_php7#extmysql)。請考慮切換到[** MySQLi **](http://php.net/manual/en/book.mysqli.php)或[** PDO **](http://php.net/manual/ en/book.pdo.php),確保您還使用[**參數化查詢**](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)來防止SQL注入: ) –

+0

首先,不要使用mysql_query,使用mysqli或者PDO並且參數化你的查詢字符串,這樣你就不會受到SQL注入的影響。 – Difster

+0

我更正$ POST到$ _POST,但仍然得到錯誤 –

回答

0

你能試試這個:

$customerName = $jsonInvoice["invoice"][0]["customerName"];

我認爲你得到了由點引起的sintax錯誤。 json_decode返回一個數組,你必須以上面寫的方式訪問屬性。 (見this進一步信息)

另外,還要建議照顧其他用戶給你約的mysqli

+0

我試過但沒有插入隊友 –