我已經創建了複雜的表單,我會嘗試提供簡化的示例。通過點擊+
按鈕可以生成更多字段。PHP數組不插入多行到數據庫
例如在形式上是字段:
通過Certificate Date Of Issue Date of Expire
[ ] [ ] [ ] +
點擊+
按鈕將其添加重複行(通過JavaScript),因此點擊形式的+
按鈕部分後的樣子:
NameOfVessel TypeOfVessel YearBuilt
[ ] [ ] [ ]
NameOfVessel TypeOfVessel YearBuilt
[ ] [ ] [ ] +
有可以按用戶需要多次點擊+
按鈕。
我有HTML格式是這樣的:
<li>
<ul class="column">
<li>
<label for="NameOfVessel">Name of Vessel</label>
<input id="NameOfVessel" type="text" name="NameOfVessel[]" class="field-style field-split25 align-left" placeholder="Name of Vessel" />
</li>
</ul>
</li>
<li>
<ul class="column">
<li>
<label for="TypeOfVessel">Type of Vessel</label>
<input id="TypeOfVessel" type="text" name="TypeOfVessel[]" class="field-style field-split25 align-left" placeholder="Type of Vessel" />
</li>
</ul>
</li>
<li>
<ul class="column">
<li>
<label for="YearBuilt">Year Built</label>
<input id="YearBuilt" type="text" name="YearBuilt[]" class="field-style field-split25 align-left" placeholder="Year Built" />
</li>
</ul>
</li>
PHP插入到數據庫中。它應該將所有添加的行中的值插入到多個數據庫表的行中,但現在它不插入任何內容。
$UserID = get_current_user_id();
$NameOfVessel = mysqli_real_escape_string($link, $_POST['NameOfVessel']);
$TypeOfVessel = mysqli_real_escape_string($link, $_POST['TypeOfVessel']);
$YearBuilt = mysqli_real_escape_string($link, $_POST['YearBuilt']);
foreach($NameOfVessel as $key=>$res) {
$sql2 = "INSERT INTO CV_SeaServices (NameOfVessel, UserId, TypeOfVessel, YearBuilt) VALUES ('$res', '$UserId[$key]', '$TypeOfVessel[$key]', '$YearBuilt[$key]')";
if(mysqli_query($link, $sql2)){
echo "Resume created successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
var_dump($NameOfVessel);
我用var_dump
,但它返回NULL
。這段代碼有什麼問題?你有什麼想法嗎?
UPDATE
我試着在下面做:
JS:
var noOfClicks = 0;
$(document).ready(function() {
$(".add-row").click(function() {
$("ul.sea-service").first().clone().appendTo(".personal-details1").append('<button class="remove">X</button>').find('input').val('');
noOfClicks += 1;
});
$("body").on('click', '.remove', function() {
$(this).closest('.sea-service').remove();
});
});
HTML:
<input id="NameOfVessel' + noOfClicks + '" type="text" name="NameOfVessel[]" class="field-style field-split25 align-left" placeholder="Name of Vessel" />
但在這種情況下,我得到了Id = ' + 'NameOfVessel' + noOfClicks + '
。據我瞭解,我需要通過JavaScript來進行連接,只是我無法正確實現。
所以 - 你的mysqli鏈接/連接可能有問題嗎?當你var_dump($ _ POST ['NameOfVessel'])''時,你會得到什麼? –