Steven
Steven

Reputation: 697

Insert into sql database dynamic form fields added

I have the following code, that inserts data into my sql database. :

<?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>

This code worked perfectly before it was altered. It used to only insert rows into the database one at a time, before I added this code :

<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>

and the ajax backend :

//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;
}

and

<?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;
}

Now, I got help with the ajax section of the code, which works(adds the form fields properly), and the POST results work fine(screened firefox's web developer tab, and it posts all of my form field data properly), the only thing that I am having issues with is how to translate MULTIPLE submissions at a time. Apparently the sql code that I have working with one submission does not work with multiple consecutive submissions, and I get the following error :

Notice: Array to string conversion in C:\wamp\www\invoice\index.php on line 131 Call Stack #TimeMemoryFunctionLocation 10.0012276928{main}( )..\index.php:0 Array" class="form-control autocomplete_txt" autocomplete="off">

and for some odd reason :

Notice: Undefined index: qty in C:\wamp\www\invoice\index.php on line 24

Any help with this matter would be GREATLY appreciated, have been troubleshooting for over a week now :P

Upvotes: 0

Views: 1819

Answers (1)

Alex
Alex

Reputation: 17289

I am not sure what you are asking for. But just to loop your arrays you can:

        $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++;
        }

Upvotes: 1

Related Questions