Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I nearly have this done but I have the following:

    <table border="1" cellpadding="2">

            <thead>
            <tr>
            <th>Item Code</th>
            <th>Description </th>
            <th>Qty </th>
            <th>Price </th>
            <th>Total </th>
            </tr>
            </thead>

<?php
$i = 1; // Count to tell you want row we are looping through… not needed just to help $grandTotal = 0;

 if (!empty($_POST)) {

// Dump POST values in array to see what the values look like
// You don't need this.  It's just to see if we have more than one row in the posted
// data from the form.
echo print_r($_POST);
// Loop through each line on invoice and do something with it... i.e. Insert into database.
foreach($_POST['itemCode'] as $row => $item) {
    echo '<tbody>';
    echo'<tr>';
    echo '<td>' . $_POST['itemCode'] . "" . "</td>";
    echo '<td>' . $_POST['itemDesc'] . "" . "</td>";
    echo '<td>' . $_POST['itemQty'] . "" . "</td>";
    echo '<td>' . $_POST['itemPrice'] . "" . "</td>";
    echo '<td>' . $_POST['itemLineTotal'] . "" . "</td>";
    echo'<tr>';
    echo'</tbody>';
    }
    }
?>
    </table>
<?php
$grandTotal .= $_POST['itemLineTotal'];



echo 'Order Total: ' . $grandTotal;

?>

But this outputs the follwing: http://i.imgur.com/JNYA6oh.jpg

This is my javascript:

            $(document).ready(function () {

                // We are overriding the autocomplete UI menu styles to create our own.
                // You can add information from the returned json array as needed
                // Just be sure that your array contains the correct value when returned
                // You'll want to modify the data/item-data.php file for the returned values

                $.ui.autocomplete.prototype._renderItem = function (ul, item) {
                    return $("<li></li>")
                        .data("item.autocomplete", item)

                        // This is the autocomplete list that is generated
                        .append("<a class='additionalInfo'>" + item.jItemCode + " - " + item.jItemDesc/* + " " +

                        // This is the hover box that is generated when you hover over an item in the list
                        "<span class='additionalInfoColor'>" +
                        "<div><h4>Item Information</h4></div>" +
                        "<div><strong>Item Ccsacsacsacsascaode:</strong> " + item.jItemCode + "</div>" +
                        "<div><strong>Qty on Hand:</strong> " + item.jQtyOnHand + "</div>" +
                        "<div><strong>Merchant:</strong> &#8364;" + item.jItemPrice + "</div>" +
                        "<div><strong>Wholesale:</strong> &#8364;" + item.jItemWholesale + "</div>" +
                        "<div><strong>Retail:</strong> &#8364;" + item.jItemRetail + "</div>" +
                        "</span> </a>"*/)

                        .appendTo(ul);
                };

                // We don't want the user to leave the page if they have started working with it so we set the
                // onbeforeload method
                $('#itemCode').focus(function () {
                    window.onbeforeunload = function () {
                        return "You haven't saved your data.  Are you sure you want to leave this page without saving first?";
                    };
                });

                // Update invoice total when item Qty or Price inputs have been updated
                $("#itemQty, #itemPrice").on('keyup', function () {
                    // Locate the row we are working with
                    var $itemRow = $(this).closest('tr');
                    // Update the price.
                    updatePrice($itemRow);
                });



                // Use the .autocomplete() method to compile the list based on input from user
                $('#itemCode').autocomplete({
                    source: 'services/fetch-item-data.php',
                    minLength: 1,
                    select:function (event, ui) {
                        var $itemrow = $(this).closest('tr');
                        // Populate the input fields from the returned values
                        $itemrow.find('#itemCode').val(ui.item.jItemCode);
                        $itemrow.find('#itemDesc').val(ui.item.jItemDesc);
                        $itemrow.find('#itemPrice').val(ui.item.jItemPrice);

                        // Give focus to the next input field to recieve input from user
                        $('#itemQty').focus();
                        return false;
                    }
                });

                /*
                 * Here's where we start adding rows to the invoice
                 */

                // Add row to list and allow user to use autocomplete to find items.
                $("#addRow").on('click', function () {

                    // Get the table object to use for adding a row at the end of the table
                    var $itemsTable = $('#itemsTable');

                    // Create an Array to for the table row. ** Just to make things a bit easier to read.
                    var rowTemp = [
                        '<tr class="item-row">',
                        '<td><i id="deleteRow" class="icon-remove"></i></td>',
                        '<td><input type="text" name="itemCode[]" class="input-medium" value="" id="itemCode" /> </td>',
                        '<td><input type="text" name="itemDesc[]" class="input-large" value="" id="itemDesc"  readonly="readonly" /></td>',
                        '<td><input type="text" name="itemQty[]" class="input-mini" value="" id="itemQty" /></td>',
                        '<td><div class="input-prepend input-append"><span class="add-on">&#8364;</span><input name="itemPrice[]" class=" input-small" id="itemPrice" type="text"></div></td>',
                        '<td><div class="input-prepend input-append"><span class="add-on">&#8364;</span><input name="itemLineTotal[]" class=" input-small" id="itemLineTotal" type="text" readonly="readonly"></div></td>',
                        '</tr>'
                    ].join('');

                    var $row = $(rowTemp);

                    // save reference to inputs within row
                    var $itemCode = $row.find('#itemCode');
                    var $itemDesc = $row.find('#itemDesc');
                    var $itemPrice = $row.find('#itemPrice');
                    var $itemQty = $row.find('#itemQty');

                    // If the last row itemCode is empty then don't let the user continue adding a row
                    if ($('#itemCode:last').val() != '') {

                        // Add row after the first row in table
                        $('.item-row:last', $itemsTable).after($row);
                        $($itemCode).focus();

                        // apply autocomplete method to newly created row
                        $row.find('#itemCode').autocomplete({
                            source:'services/fetch-item-data.php',
                            minLength:1,
                            select:function (event, ui) {
                                $itemCode.val(ui.item.jItemCode);
                                $itemDesc.val(ui.item.jItemDesc);
                                $itemPrice.val(ui.item.jItemPrice);
                                // Give focus to the next input field to receive input from user
                                $itemQty.focus();
                                return false;
                            }
                        });

                        // Remove row when clicked
                        $row.find("#deleteRow").on('click', function () {
                            // Remove this row we clicked on
                            $(this).parents('.item-row').remove();
                            // Show alert we removed the row
                            updateMessage('.alert', 'Item was removed!', 2000);
                            // Hide delete Icon if we only have one row in the list.
                            if ($(".item-row").length < 2) $("#deleteRow").hide();
                            // Update total
                            update_total();
                        });

                        // Update the invoice total on keyup when the user updates the item qty or price input
                        // ** Note: This is for the newly created row
                        $row.find("#itemQty, #itemPrice").on('keyup', function () {
                            // Locate the row we are working with
                            var $itemRow = $(this).closest('tr');
                            // Update the price.
                            updatePrice($itemRow);
                        });


                    } else {
                        $('.alert').fadeIn('slow').html('You need to complete the item inputs');
                    }

                    // End if last itemCode input is empty
                    return false;
                });

            }); // End DOM


            /* Description: Update price function
            *  @param: $itemRow - Row Object
            * */

             var updatePrice = function($itemRow){
                // Calculate the price of the row.  Remove and $ so the calculation doesn't break
                var price = $itemRow.find('#itemPrice').val().replace("$", "") * $itemRow.find('#itemQty').val();
                price = roundNumber(price, 2);
                isNaN(price) ? $itemRow.find('#itemLineTotal').val("N/A") : $itemRow.find('#itemLineTotal').val(price);
                update_total();
            };

            var update_total = function() {
                var total = 0;
                $('input#itemLineTotal').each(function (i) {
                    price = $(this).val().replace("$", "");
                    if (!isNaN(price)) total += Number(price);
                });

                total = roundNumber(total, 2);
                $('#invGrandTotal').html("<h4>&#8364;" + total + "</h4>");

            };


            // Update message
            var updateMessage = function(msgType, message, delay){
                $('#alert').fadeIn('slow').addClass(msgType).html(message).delay(delay).fadeOut('slow');
            };


            //########################################################################################################################

            // from http://www.mediacollege.com/internet/javascript/number/round.html
            function roundNumber(number, decimals) {
                var newString;// The new rounded number
                decimals = Number(decimals);
                if (decimals < 1) {
                    newString = (Math.round(number)).toString();
                } else {
                    var numString = number.toString();
                    if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
                        numString += ".";// give it one at the end
                    }
                    var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
                    var d1 = Number(numString.substring(cutoff, cutoff + 1));// The value of the last decimal place that we'll end up with
                    var d2 = Number(numString.substring(cutoff + 1, cutoff + 2));// The next decimal, after the last one we want
                    if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
                        if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
                            while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
                                if (d1 != ".") {
                                    cutoff -= 1;
                                    d1 = Number(numString.substring(cutoff, cutoff + 1));
                                } else {
                                    cutoff -= 1;
                                }
                            }
                        }
                        d1 += 1;
                    }
                    if (d1 == 10) {
                        numString = numString.substring(0, numString.lastIndexOf("."));
                        var roundedNum = Number(numString) + 1;
                        newString = roundedNum.toString() + '.';
                    } else {
                        newString = numString.substring(0, cutoff) + d1.toString();
                    }
                }
                if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
                    newString += ".";
                }
                var decs = (newString.substring(newString.lastIndexOf(".") + 1)).length;
                for (var i = 0; i < decimals - decs; i++) newString += "0";
                //var newNumber = Number(newString);// make it a number if you like
                return newString; // Output the result to the form field (change for your purposes)
            }

Obviously it is not getting the correct information from the array for the table but is outputting the correct values at the top? please please help

share|improve this question

3 Answers 3

Since each $_POST item is an array, loop and pull out the individual elements:

echo '<tbody>';
for ($i = 0; $i < count($_POST['itemCode']); $i++) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($_POST['itemCode'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemDesc'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemQty'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemPrice'][$i]) . "</td>";
    echo '<td>' . htmlspecialchars($_POST['itemLineTotal'][$i]) . "</td>";
    echo '</tr>';
}
echo '</tbody>';

P.S. Use htmlspecialchars when echoing user data to prevent XSS and prevent any < characters in the text from eating the document.

share|improve this answer
    
Thanks sooooooooooooooooooooooooooo much Boann! That did it! Thank you! –  Dom Dec 18 '13 at 15:42

You are having an array of values, already you are iterating it as key value pair. Here $row will be key of the array i.e index of array

So try this

foreach($_POST['itemCode'] as $row => $item) {
    echo'<tr>';
     echo '<td>' . $_POST['itemCode'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemDesc'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemQty'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemPrice'][$row] . "" . "</td>";
     echo '<td>' . $_POST['itemLineTotal'][$row] . "" . "</td>";
    echo'<tr>';

}

You can find more info here

share|improve this answer
    
one final one guys. How can I pull in the order total? –  Dom Dec 18 '13 at 16:10
    
$orderTotal += ($_POST['itemQty'][$row] * $_POST['itemPrice'][$row]); Also please use htmlspecialchars As Mr.Boann has suggested. –  Nouphal.M Dec 18 '13 at 16:14
    
Cool that only gives me the last total see here i.imgur.com/ITTACMC.jpg –  Dom Dec 18 '13 at 16:25
    
You have to initialize $orderTotal =0 before the foreach loop –  Nouphal.M Dec 18 '13 at 16:28
    
sorry that doesnt work please see original question at the top –  Dom Dec 18 '13 at 17:08

I think this is exactly what you are after. Just did this about an hour ago for a project I was working on.

function hash2table($data, $show_row_numbers = true) {
    $return = false;
    if($data) {
        $keys = array_keys($data[0]);
        $keys = array_merge(array(""), $keys);
        $return = "<table>";
        $return .= "<thead>";
        $return .= "<tr>";
        foreach($keys as $key => $value) {
            $return .= "<th>{$value}</th>";
        }
        $return .= "<tr>";
        $return .= "</thead>";
        $return .= "<tbody>";
        foreach($data as $row_key => $row) {
            $return .= "<tr>";
            if($show_row_numbers) $return .= "<th>{$row_key}</th>";
            foreach($row as $key => $value) {
                $return .= "<td>{$value}</td>";
            }
            $return .= "</tr>";
        }
        $return .= "</tbody>";
        $return .= "</table>";
        return $return;
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.