dtc9222 2013-11-07 19:29
浏览 156
已采纳

如何将动态添加的内容存储到数据库

I am having a few trouble storing my content into the database. The table/rows are dynamically generated using jquery! but when i click the submit button, just a row of numbers is stored in my database table even when i store text values. Here is my jquery code:

function addRow(tableID) { 
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = "<input type='text' name='Obstacle'>";
var cell3 = row.insertCell(2);
cell3.innerHTML = "<select name='Likelihood'> <option value='1'>Low</option> <option value='2'>Medium</option><option value='3'>High</option>/>";

var cell4 = row.insertCell(3);
cell4.innerHTML = "<select name='Severity'> <option value='1'>Low</option> <option value='2'>Medium</option><option value='3'>High</option>/>";

var cell5 = row.insertCell(4);
cell5.innerHTML = "<select name='Priority'> <option value='1'>Low</option> <option value='2'>Medium</option><option value='3'>High</option>/>";
}

Here is my html:

<div class="compTable">
<form action="" method="post">  

<TABLE width="425" border="1">
<thead>
<tr>
<th width="4"></th>
<th width="100">Obstacle</th>
<th width="50">Likelihood</th>
<th width="50">Severity</th>
<th width="50">Priotity</th>
</tr>
</thead>
<tbody id="dataTable">
</tbody>
</TABLE>
<INPUT type="submit" value="Save" name="submit" />
<INPUT type="button" value="Add Obstacle" onClick="addRow('dataTable')" />
<INPUT type="button" value="Delete Obstacle" onClick="deleteRow('dataTable')" />
</form>
</div>

and finally my php code:

if(isset($_POST['submit'])){
$user = $_SESSION['user']['FullName'];
$obstacleDec = isset($_POST["Obstacle"][$key]);
$likelihoodScale = isset($_POST["Likelihood"][$key]);
$severityScale = isset($_POST["Severity"][$key]);
$priorityScale = isset($_POST["Priority"]);

foreach ($_POST as $key => $value){
$sql = "INSERT INTO obstacles (ObstacleID, ObstacleDescription, Priority, Uncertainty, Severity, UserName, ComplianceID, Accepted)
VALUES (:ID, :obstacleDec, :priorityScale, :likelihoodScale, :severityScale, :aUser, :compID, :accepted)";

try{
$stmt = $db->prepare($sql);
$result= $stmt->execute(array(':ID'=>'', ':obstacleDec'=>$obstacleDec,':likelihoodScale'=>$likelihoodScale, ':severityScale'=>$severityScale,':priorityScale'=>$priorityScale, ':aUser'=>$user, ':compID'=>'', ':accepted'=>'' ));
}
catch(PDOException $ex){ 
die("Failed to run query: " . $ex->getMessage());
}

header("Location: obstacles.php"); 
die("Redirecting to obstacles.php");
if(!$sql){
die("error inserting values");
}
else{
die("successfully inserted the values");
}
}
}

Thanks for the help

  • 写回答

1条回答 默认 最新

  • douguabu8960 2013-11-07 19:37
    关注

    If you mean you only get the last filled data from each different fields that happens because your fields name is not a array, change the names adding on end []

    Like that:

    <input type='text' name='Obstacle[]'>
    

    And the same for the others fields. Also you can optimize your php code a little bit more like that bellow. I don't have your code but you can use var_dump($_POST) to check and correct.

    code updated

    <?php
    //simulating data from form
    $_POST = array(
                   'Obstacle' => array('ob1', 'ob2', 'ob3'),
                   'Likelihood' => array('l1', 'l2', 'l3'),
                   'Severity' => array('s1', 's2', 's3'),
                   'Priority' => array('p1', 'p2', 'p3'),
                   );
    $user = 1;
    
    //the code
     $sql = "INSERT INTO obstacles (ObstacleDescription, Priority, Uncertainty, Severity, UserName, ComplianceID, Accepted)
        VALUES (:ID, :obstacleDec, :priorityScale, :likelihoodScale, :severityScale, :aUser, :compID, :accepted)";
        // $stmt = $db->prepare($sql);
    
        for ($i=0; $i<count($_POST['Obstacle']); $i++) {
            $values = array(':obstacleDec'=>$_POST['Obstacle'][$i],':likelihoodScale'=>$_POST['Likelihood'][$i], ':severityScale'=>$_POST['Severity'][$i],':priorityScale'=>$_POST['Priority'][$i], ':aUser'=>$user, ':compID'=>'', ':accepted'=>'' );
            // var_dump($values);
            try{
                $result= $stmt->execute($values);
            }
            catch(PDOException $ex){
                die("Failed to run query: " . $ex->getMessage());
            }
        }
    
        header("Location: obstacles.php");
        die("Redirecting to obstacles.php");
        //the ifs you have here are not necessary, your code will never get here
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败