插入sql数据库动态表单字段添加

时间:2015-05-18 14:02:11

标签: php mysql ajax

我有以下代码,将数据插入我的sql数据库。 :

<?php

require 'database.php';

if(!empty($_GET['wid']))      { $wid = $_GET['wid'];  }
elseif(!empty($_POST['wid'])) { $wid = $_POST['wid']; }
else                         { $wid = null;         }

if ( !empty($_POST)) {
        // keep track validation $

        $ModelError       = null;
        $DescriptionError = null;
        $CostError        = null;
        $RetailError      = null;
        $QuantityError    = null;

        // keep track post values

        $Model        = $_POST['model'];
        $Description  = $_POST['description'];
        $Cost         = $_POST['cost'];
        $Retail       = $_POST['retail'];
        $Quantity     = $_POST['qty'];

        // validate input
        $valid = true;
        if (empty($Model)) {
            $ModelError = 'Please enter Model';
            $valid = false;
        }
        if (empty($Description)) {
            $DescriptionError = 'Please enter Description';
            $valid = false;
        }
        if (empty($Cost)) {
            $CostError = 'Please enter Cost';
            $valid = false;
        }
        if (empty($Retail)) {
            $RetailError = 'Please enter Retail';
            $valid = false;
        }
        if (empty($Quantity)) {
            $QuantityError = 'Please enter Quantity';
            $valid = false;
        }

if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO items (WID, model, description, cost, retail, qty) values(?, ?, ?, ?, ?, ?);";
            $q = $pdo->prepare($sql);
            $q->execute(array($wid,$Model, $Description, $Cost, $Retail, $Quantity));

            Database::disconnect();
            header("Location: index.php");
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Workorder System</title>

    <!-- Bootstrap core CSS -->
    <link href="css/jquery-ui.min.css" rel="stylesheet">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/datepicker.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/sticky-footer-navbar.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>


    <!-- Begin page content -->
    <div class="container content">
        <div class='row'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
                <h1 class="text-center title">Workorder System </h1>
            </div>
        <h2>&nbsp;</h2>
        <div class='row'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
            <form class="form-horizontal" action="index.php" method="post">
            <input type="hidden" name="wid" value="<?php echo htmlentities($wid); ?>">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
                            <th width="15%">ID</th>
                            <th width="15%">Model #</th>
                            <th width="38%">Description</th>
                            <th width="15%">Cost</th>
                            <th width="15%">Retail</th>
                            <th width="15%">Quantity</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                            <input class="case" type="checkbox"/></td>
                            <td>
                            <input type="text" data-type="ID" name="idNo[]" id="idNo_1" class="form-control autocomplete_txt" autocomplete="off"></td>
                            <td>

                            <div class="control-group <?php echo !empty($ModelError)?'error':'';?>">
                                    <div class="controls">
                                        <input type="text" data-type="model" name="model[]" id="model_1" placeholder="Model" value="<?php echo !empty($Model)?$Model:'';?>" class="form-control autocomplete_txt" autocomplete="off">
                                            <?php if (!empty($ModelError)): ?>
                                                <span class="help-inline"><?php echo $ModelError;?></span>
                                            <?php endif; ?>
                                    </div>
                            </div>

                            </td>
                            <td>

                            <div class="control-group <?php echo !empty($DescriptionError)?'error':'';?>">
                                    <div class="controls">
                                        <input type="text" data-type="description" name="description[]" id="description_1" placeholder="Description" value="<?php echo !empty($Description)?$Description:'';?>" class="form-control autocomplete_txt" autocomplete="off">
                                            <?php if (!empty($DescriptionError)): ?>
                                                <span class="help-inline"><?php echo $DescriptionError;?></span>
                                            <?php endif; ?>
                                    </div>
                            </div>

                            </td>   
                            <td>

                            <div class="control-group <?php echo !empty($CostError)?'error':'';?>">
                                    <div class="controls">
                                        <input type="text" data-type="cost" name="cost[]" id="cost_1" placeholder="Cost" value="<?php echo !empty($Cost)?$Cost:'';?>" class="form-control autocomplete_txt" autocomplete="off">
                                            <?php if (!empty($CostError)): ?>
                                                <span class="help-inline"><?php echo $CostError;?></span>
                                            <?php endif; ?>
                                    </div>
                            </div>

                            </td>
                            <td>

                            <div class="control-group <?php echo !empty($RetailError)?'error':'';?>">
                                    <div class="controls">
                            <input type="text" data-type="retail" name="retail[]" id="retail_1" placeholder="Retail" value="<?php echo !empty($Retail)?$Retail:'';?>" class="form-control autocomplete_txt" autocomplete="off">
                            <?php if (!empty($RetailError)): ?>
                                                <span class="help-inline"><?php echo $RetailError;?></span>
                                            <?php endif; ?>
                                    </div>
                            </div>

                            </td>
                            <td>

                            <div class="control-group <?php echo !empty($QuantityError)?'error':'';?>">
                                    <div class="controls">
                            <input type="number" name="quantity[]" id="quantity_1" placeholder="Quantity" value="<?php echo !empty($Quantity)?$Quantity:'';?>" class="form-control autocomplete_txt" autocomplete="off">
                            <?php if (!empty($QuantityError)): ?>
                                                <span class="help-inline"><?php echo $QuantityError;?></span>
                                            <?php endif; ?>
                                    </div>
                            </div>

                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class='row'>
            <div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
                <button class="btn btn-danger delete" type="button">- Delete</button>
                <button class="btn btn-success addmore" type="button" id="Add">+ Add More</button>
            </div>
        </div>
        <h2>Notes: </h2>
        <div class='row'>
            <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
                <div class="form-group">
                    <textarea class="form-control" rows='5' id="notes" placeholder="Your Notes"></textarea>
                </div>
            </div>
        </div>      
        <div class="form-actions">
                          <button type="submit" class="btn btn-success">Create</button>
                          <a class="btn" href="index.php">Back</a>
                        </div>
    </div>

    <script src="js/jquery.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/bootstrap-datepicker.js"></script>
    <script src="js/auto.js"></script>
  </body>
</html>

此代码在更改之前完美运行。在我添加此代码之前,它一次只能在数据库中插入一行:

<div class='row'>
            <div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
                <button class="btn btn-danger delete" type="button">- Delete</button>
                <button class="btn btn-success addmore" type="button" id="Add">+ Add More</button>
            </div>
        </div>

和ajax后端:

//adds extra table rows
var i=$('table tr').length;
$(".addmore").on('click',function(){
    html = '<tr>';
    html += '<td><input class="case" type="checkbox"/></td>';
    html += '<td><input type="text" data-type="ID" name="idNo[]" id="idNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="model" name="model[]" id="model_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="description" name="description[]" id="description_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="cost" name="cost[]" id="cost_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="retail" name="retail[]" id="retail_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
    html += '<td><input type="text" data-type="quantity" name="quantity[]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
    html += '</tr>';
    $('table').append(html);
    i++;
});

//to check all checkboxes
$(document).on('change','#check_all',function(){
    $('input[class=case]:checkbox').prop("checked", $(this).is(':checked'));
});

//deletes the selected table rows
$(".delete").on('click', function() {
    $('.case:checkbox:checked').parents("tr").remove();
    $('#check_all').prop("checked", false); 
    calculateTotal();
});

//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
    type = $(this).data('type');

    if(type =='ID' )autoTypeNo=0;
    if(type =='model' )autoTypeNo=1;    

    $(this).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                method: 'post',
                data: {
                   name_startsWith: request.term,
                   type: type
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[autoTypeNo],
                            value: code[autoTypeNo],
                            data : item
                        }
                    }));
                }
            });
        },
        autoFocus: true,            
        minLength: 0,
        select: function( event, ui ) {
            var names = ui.item.data.split("|");                        
            id_arr = $(this).attr('id');
            id = id_arr.split("_");
            $('#idNo_'+id[1]).val(names[0]);
            $('#model_'+id[1]).val(names[1]);
            $('#description_'+id[1]).val(names[2]);
            $('#cost_'+id[1]).val(names[3]);
            $('#retail_'+id[1]).val(names[4]);
            $('#quantity_'+id[1]).val(1);
            $('#total_'+id[1]).val( 1*names[4] );
            calculateTotal();
        }               
    });
});

//It restrict the non-numbers
var specialKeys = new Array();
specialKeys.push(8,46); //Backspace
function IsNumeric(e) {
    var keyCode = e.which ? e.which : e.keyCode;
    console.log( keyCode );
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
    return ret;
}

<?php

require_once 'config.php';
if(!empty($_POST['type'])){
    $type = $_POST['type'];
    $name = $_POST['name_startsWith'];
    $query = "SELECT ID, model, category, subcategory, description, cost, retail FROM products where UPPER($type) LIKE '".strtoupper($name)."%'";
    $result = mysqli_query($con, $query);
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['ID'].'|'.$row['model'].'|'.$row['description'].'|'.$row['cost'].'|'.$row['retail'];
        array_push($data, $name);
    }   
    echo json_encode($data);exit;
}

现在,我得到了代码的ajax部分的帮助,它可以正常工作(正确添加表单字段),并且POST结果正常工作(屏蔽了firefox&#39的Web开发人员选项卡,并且它发布了我的所有表单正确的字段数据),我遇到的唯一问题是如何一次翻译MULTIPLE提交。显然,我使用一个提交的sql代码不能与多个连续提交一起使用,并且我收到以下错误:

  

注意:第131行C:\ wamp \ www \ invoice \ index.php中的数组到字符串转换调用堆栈#TimeMemoryFunctionLocation 10.0012276928 {main}().. \ index.php:0数组&#34; class =&#34; form-control autocomplete_txt&#34;自动填充=&#34;关闭&#34;&GT;

出于某些奇怪的原因:

  

注意:未定义的索引:第24行的C:\ wamp \ www \ invoice \ index.php中的数量

任何有关此事的帮助都会非常感激,现在已经进行了一周多的故障排除:P

1 个答案:

答案 0 :(得分:1)

我不确定你要求的是什么。但只需循环播放数组即可:

        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO items (WID, model, description, cost, retail, qty) values(?, ?, ?, ?, ?, ?);";
        $q = $pdo->prepare($sql);
        $idx = 0;
        foraech ($Model as $model_idx) {
            $q->execute(array($wid,$model_idx, $Description[$idx], $Cost[$idx], $Retail[$idx], $Quantity[$idx]));
            $idx++;
        }