[英]Passing an array of objects to php
我正在嘗試通過 ajax 將一組對象傳遞給我的 php 文件。 基本上,一旦它到達我的 php 文件,我想遍歷數組中的每個對象,並將其屬性插入數據庫。
這是我設置傳遞對象數組的方法:
for(i=1;i<totalRowCount;i++){
let currentRow = table.rows[i];
itemArray.push({
'itemId' : currentRow.cells[0].innerText,
'memo' : currentRow.cells[1].innerText,
'project' : currentRow.cells[2].innerText,
'department' : currentRow.cells[3].innerText,
'location' : currentRow.cells[4].innerText,
'qty' : currentRow.cells[5].innerText,
'price' : currentRow.cells[6].innerText
})
}
在我的 ajax 調用中,我傳遞了我的數據。 我傳入的所有屬性值都只是單個值,除了 itemArray 是我的對象數組:
$.ajax({
type: 'POST',
url: 'upload.php',
data:{
'firstName' : firstName,
'lastName' : lastName,
'email' : email,
'date' : date,
'vendor' : vendor,
'txnCurrency' : txnCurrency,
'expDate' : expDate,
'vendorDoc' : vendorDoc,
'justification' : justification,
'desc' : desc,
'itemTotals' : itemTotals,
'subTotals' : subTotals,
'transTotal' : transTotal,
'itemArray' : itemArray
},
success: function(data){
alert('hi');
}
});
我的問題是我真的不確定 itemArray 到達 php 時的格式。 我現在正在嘗試循環,但不知何故我把它搞砸了:
foreach($itemArray as $x) {
$sql2 = $mysqli->prepare("INSERT INTO entries (po_id, memo, project_id, department, locn, qty, price) VALUES (?,?,?,?,?,?,?)");
$sql2->bind_param($last_id,$x['memo'],$x['project'],$x['department'], $x['location'], $x['qty'], $x['price']);
$conn->query($sql2);
}
我將如何格式化它以使其有效? 基本上我想為數組中的每個對象單獨插入到我的數據庫中。
我假設錯誤最終出現在我的 SQL 語句的格式中。 在將對象發送到 php 之前,我還需要 JSON.Stringify 我的對象,然后在它到達那里后使用 json_decode。 這是我的解決方案語法明智的:
foreach($fixedArray as $x) {
$memo = $x['memo'];
$project = $x['project'];
$department = $x['department'];
$location = $x['location'];
$qty = $x['qty'];
$price = $x['price'];
$sql2 = ("INSERT INTO entries (po_id, memo, project_id, department, locn, qty, price) VALUES ('$last_id', '$memo', '$project', '$department', '$location', '$qty', '$price')");
$conn->query($sql2);
$counter = $counter + 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.