我这里有我的JS脚本,当用户点击“添加项目”按钮时,它会动态添加三个文本框。保存在数据库中时,三个文本框具有不同的字段。但似乎在我的PHP代码中它没有从文本框中捕获任何值。在数据库中,它只显示'Array'。请帮我!谢谢!
<script language="javascript">
row_no=0;
function addRow(tbl,row){
row_no++;
if (row_no<=20){
if (row_no<=20){
if (row_no>=10){
var textbox = row_no+'.) <input type="text" size = "50" maxlength= "50" name= "desk_user[]">';}
if (row_no<10){
var textbox = row_no+'. ) <input type="text" size = "20" maxlength= "50" name= "desk_user[]">';}
var textbox2 = '<input type="text" size = "60" maxlength= "250" name= "desk_report[]">';
var textbox3 = '<input type="text" size = "60" maxlength= "250" name= "desk_action[]">';
var tbl = document.getElementById(tbl);
var rowIndex = document.getElementById(row).value;
var newRow = tbl.insertRow(row_no);
var newCell = newRow.insertCell(0);
newCell.innerHTML = textbox;
var newCell = newRow.insertCell(1);
newCell.innerHTML = textbox2;
var newCell = newRow.insertCell(2);
newCell.innerHTML = textbox3;
}
if (row_no>20){
alert ("Too Many Items. Limit of 20.");
}
}
}
</script>
我的PHP代码:
<?php
$con = mysql_connect ("localhost","root","nasi") or die
('cannot connect to database error: '.mysql_error());
if (isset($_POST['desk_user']) &&
isset($_POST['desk_report']) &&
isset($_POST['desk_action']))
{
$desk_user = $_POST['desk_user'];
$desk_report = $_POST['desk_report'];
$desk_action = $_POST['desk_action'];
if (!empty($desk_user)&& !empty($desk_report)&& !empty($desk_action)) {
mysql_select_db("csr", $con);
$sql = "INSERT INTO `desktoplaptop` (`desk_user`,`desk_report`,`desk_action`) VALUES ('$_POST[desk_user]','$_POST[desk_report]','$_POST[desk_action]') ";
if ($sql_run = mysql_query($sql)) {
echo 'ok.';
}
else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
}
?>
答案 0 :(得分:3)
您将值视为数组,因为您已将文本框名称定义为数组
<input type="text" size = "20" maxlength= "50" name= "desk_user[]">
像这样修改你的代码
<?php
$con = mysql_connect ("localhost","root","nasi") or die
('cannot connect to database error: '.mysql_error());
if (isset($_POST['desk_user']) &&
isset($_POST['desk_report']) &&
isset($_POST['desk_action']))
{
$desk_user_arr = $_POST['desk_user'];//contains array value
$desk_report = $_POST['desk_report'];//contains array value
$desk_action = $_POST['desk_action'];//contains array value
foreach($desk_user_arr as $key=>$desk_user) { //Loop through arrays
if (!empty($desk_user) && !empty($desk_report[$key]) && !empty($desk_action[$key])) {
mysql_select_db("csr", $con);
$sql = "INSERT INTO `desktoplaptop` (`desk_user`,`desk_report`,`desk_action`) VALUES ('$desk_user','$desk_report[$key]','$desk_action[$key]') ";
if ($sql_run = mysql_query($sql)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
}
}
?>