Jump to content

trying to insert multple form data into msyql database

Go to solution Solved by ginerjm,

Recommended Posts

So I'm basically trying to make a simple Purchase Order program and I have HTML like this.

Now my problem is when i do something like if(isset($_POST['item_number'.$count])) it will always return $count number even if item_number isn't set.

So what would be better way of sending this data via post to get it into mysql database.


	while($num_rows > 0){
	echo "<tr>";
	echo '<td><input class="item" name="item_number'.$count.'"></td>';
	echo ' <td><input class="description" name="description'.$count.'"> </td>';
	echo '<td><input class="quantity" name="quantity'.$count.'"></td>';
	echo '<td><input class="unit_price" name="unit_price'.$count.'"></td>';
	echo '<td><input class="total_price"></td>';
	echo '</tr>';




Link to comment
Share on other sites

There are different strategies for handling multiple entries, but the one employed most frequently is to implement some javascript that will allow you to add a new form group to the table dynamically, using an "Add another item" button or something similar.

Rather than trying to make the input names unique, utilize array name syntax like so:

echo '<td><input class="item" name="item_number[]"></td>';

Once you do this, $_POST['item_number'] will be an array, and you can foreach() through it to validate data and do as many inserts as you have validated items.

Hopefully, it is clear that you will use the array syntax with all the fields, and when you dynamically add a new input row, be sure to also use that syntax for the dynamically created row/input group.

Link to comment
Share on other sites

As gizmola said,name them as array items...


Your post data will then look like this (for brevity, 3 recs with 3 fields)

$_POST = Array
    [item_number] => Array
            [0] => 1
            [1] => 2
            [2] => 3

    [decription] => Array
            [0] => aaa
            [1] => bbb
            [2] => ccc

    [quantity] => Array
            [0] => 10
            [1] => 20
            [2] => 30


To make life easier when usin PDO prepared inserts, you could name them like this ...


which gives post data like this...

    [record] => Array
            [0] => Array
                    [item_number] => 1
                    [description] => aaa
                    [quantity] => 10

            [1] => Array
                    [item_number] => 2
                    [description] => bbb
                    [quantity] => 20

            [2] => Array
                    [item_number] => 3
                    [description] => ccc
                    [quantity] => 30



wihich gives convenient arrays to use in your insertion statement

$stmt->execute( $_POST['record'][$i] );


Link to comment
Share on other sites

  • Solution

While you have 2 very reliable responses to answer your question, I see no problem with the way you have designed your page.  I think the problem you are having is you are not reading the input delivered to your script properly.  

You probably have  a loop that is simply trying to check if an input is present rather than if it is empty, ie, not entered.  As we all know your $_POST array is going to have all of the text inputs present (which you really should be designating) even if the user did not put something into them.  So - in your processing logic, look for a value in your loop and not just whether isset() is true.  It's always true (unless it's a checkbox or a radio) so that is not a good test.  Check if it has something in it instead.  Choose the key field that indicates whether the user is posting something to that data row and rely on your testing of that item.  If it is empty then do a continue and move on to the next row.

Just my $.02.

Link to comment
Share on other sites

Posted (edited)

Here is how I would write it:

$num_rows = 3;
echo "<table>";
for ($count = 1; $count <= $num_rows; $count++)
	echo "<tr>
	<td>Item: <input type='text' class='item' size=3 name='item_number$count' value='$count'></td>
	<td>Desc.: <input type='text' class='description' size=20 name='description$count'></td>
	<td>Qty.: <input type='text' class='quantity' size=2 name='quantity$count'></td>
	<td>Unit $: <input type='text' class='unit_price' size=8 name='unit_price$count'></td>
	<td>What name is this? <input type='text' size=8 class='total_price'></td>
echo "</table>";

I have assigned size attributes but you should not use size.  Setup a class instead for the width of your input values.  And - you should make the 'labels' I created actual html <label> tags to be proper.

Edited by ginerjm
Link to comment
Share on other sites

Thanks everyone for the input.

I looks like I need for a rewrite on most of my stuff, but I'm learning.  I found a quick solution that solved my problem by changing my test to if(!empty ($_POST['item_number$count'])).  I will go back and work with some of the other methods as I think the code will be cleaner that way.


Thanks again for the help

Link to comment
Share on other sites

11 hours ago, gizmola said:

There are different strategies for handling multiple entries, but the one employed most frequently is to implement some javascript that will allow you to add a new form group to the table dynamically, using an "Add another item" button or something similar.


Any recommendations on a way to quickly learn it in terms of quality sources?  When you say javascript, I'm assuming you mean jquery or ajax.  I'm still pretty new to the web development, so I'm learning the hard way.

Link to comment
Share on other sites

In this case you don't need ajax.

The way to think about a feature like this, is to make sure you are clear on what is happening in the browser when you are on a web page that has already been delivered to your browser in an HTTP response.  The page has the DOM loaded, and is running completely disconnected from the server.  If you were looking at network traffic, you would likely see that there is no connection to the web server open.

So the way to think about it, is that you have a javascript application running in your browser.

A traditional form, when submitted, is a new request to the server.  Depending on if it's GET or POST method, a new HTTP request gets sent, the browser waits for the response, and the entire DOM is rebuilt based upon the response data, which is going to be more HTML (along with associated javascript, css etc.).

Ajax was added to the DOM api, in order for there to be a way that a page could send and receive data, without this entirely new HTTP request/response.  It's an HTTP request through javascript, where the data returned can then be evaluated within the running javascript and used to update the page.   So ajax is an alternative to standard HTTP request/response, typically with forms, but now, with many other aspects of dynamic DOM manipulation with javascript.

So, hopefully that helps you understand ajax, and why it is extremely beneficial and useful in modern web applications.  In this case, it is absolutely not needed.

So to go back to the page in your browser, that page is running locally as an application hosted within the browser.  It has to be able to handle mouse and keyboard events, and unless it's a standard click on a link, or a submit button for a form, there won't be a new http request generated by default.

What you have is a form, where you have rendered a table inside of it with a series of HTML form elements to be filled in.  

You want to be able to add a new set of these form elements, and all that is required there is javascript, running locally to dynamically manipulate the DOM and add a new row to the table with a new set of table elements.  

jquery is the grandfather of javascript frameworks.  It was designed to make it easy for people to do DOM manipulation of the type you need, and it also has functions that make ajax easy.  Most developers who have been around a while, have probably used it in the past, and it was part of the first really popular css ui framework (Twitter Bootstrap).  It's got a lot of capabilities, but it's also a bit bloated by today's standards.  As things have evolved and changed in the javascript UI world, a lot of other libraries and javascript frameworks have emerged, and many of the things jquery was used for in the past are being done instead with a framework like react or vue.   So I won't show you how to do this in jquery, since if you already aren't using it in some way, I won't suggest to start down a path that isn't being used for new development.

Here is some simple javascript that will dynamically add a new row to an existing table.  It isn't exactly matched to what you have now, but is based on it.

function addRow() {
    console.log('clicked addrow');
    const table = document.getElementById("form_wrapper");
    const row = table.insertRow(1);
    let c1 = row.insertCell(0);
    let c2 = row.insertCell(1);
    let c3 = row.insertCell(2);
    let c4 = row.insertCell(3);
    c1.innerHTML = '<label>Item:</label><input type="text" class="item" size="5" name="item_number[]">';
    c2.innerHTML = '<label>Desc:</label><input type="text" class="description" size="20" name="description[]">';
    c3.innerHTML = '<label>Qty:</label>        <input type="text" class="quantity" size="3" name="quantity[]">';
    c4.innerHTML = '<button type="button" name="add_row" onclick="addRow()">+</button>';


Here's a codepen, for demonstration purposes:  https://codepen.io/gizmola/pen/jOQLKBd

I think you'll find that this use of document.getElementById, is the most common way to select an item that has an id attribute.  There should only ever be one element on a page with that id, so it's perfect for selecting the table.  Once you have the table element you can dynamically add a new row, and the cells you need.



Link to comment
Share on other sites

I should add, you could attach this code to the onclick of a button you have separately, or add to every new row.  Obviously, as you can see, setting the onclick for the buttons this way makes it very easy to render an equivalent button without having to also manage a call to addEventListener for each new row that's generated.  If you only want to have one button for adding new rows, then I'd give that button an id and use element.addEventListener instead.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.