html dynamic form, pass multiple values through post and insert mysql - php

i have this database
and this form, dynamically generated from the database
<table border="1" cellspacing="0" cellpadding="6">
<tr bgcolor="#CCCCCC">
<td><strong>product id</strong></td>
<td><strong>product name</strong></td>
<td><strong>product price</strong></td>
<td><strong>quantity</strong></td>
</tr>
<form method="post" action="insert.php">
<?php
$query = $dbh->query('SELECT * FROM products');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row)
{
?>
<tr>
<td><?php echo $row['product_id']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_price']; ?></td>
<td><input name="quantity" type="text" value="0"></td>
</tr>
</form>
<?php } ?>
</table>
<br>
<input type="submit" value="Add Records">
the quantity in the form is a textbox so i can modify it.
I would like to enter the quantities and the pressing the button to insert the values in the order_products table (including the quantity).
1) How can i pass ALL the quantities and product_id (and the rest) to the next page through post? (until now i know how to pass single values)
2) is there a better way to achieve it?
3) the insert statements should be in the same page or the page where i get the post vars?
db scheme
http://i.stack.imgur.com/oqdOy.jpg
thanks
Rob

1) First, you have to wrap your <input>s inside a single form (move your </form> tag after your <input type="submit" value="Add Records">, the way you have it now closes the <form> tag at first iteration) and submit it via HTTP POST method. Then, based on your schema, the only field you'll have to insert aside of quantity is product_id, which value you can assign inside a hidden field, like:
<?php
echo "<input type='hidden' name='pid_$row['product_id']' value='$row['product_id']'>";
echo $row['product_id'];
?>
Notice that you can still echo the value itself for viewing purposes. You also have to generate your quantity <input> field name property dynamically, otherwise $_POST will overwrite values when their keys are the same.
<?php
echo "<input type='text' name='pid-qtd_$row['product_id']'>";
?>
2) It depends on your development priorities. There are some frameworks out there that might simplify your process. I'd recommend you to keep all your DB queries and connection data within a DB helper class and require it wherever you need it.
3) Since you're using PDO, I assume you have an OOP design, which implies in doing that at your DB helper class or such. The page receiving the HTTP request must require your helper and deal with the $_POST parsing to parameters to its query methods. Don't forget to prepare your statements and parameterizing your queries.

Using hidden element you can post your data to second page. Using counter variable you can add dynamic form element and post it into second page.
<form method="post" action="test2.php">
<table border="1" cellspacing="0" cellpadding="6">
<tr bgcolor="#CCCCCC">
<td><strong>product id</strong></td>
<td><strong>product name</strong></td>
<td><strong>product price</strong></td>
<td><strong>quantity</strong></td>
</tr>
<?php
$query = $con->query('SELECT * FROM product'); //your query goes here
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$i=0; //counter variable
foreach ($results as $row)
{
?>
<tr>
<td>
<?php echo $row['prod_id']; ?>
<input type="hidden" name="prod_id<?php echo $i; ?>" value="<?php echo $row['prod_id']; ?>" />
</td>
<td>
<?php echo $row['prodname']; ?>
<input type="hidden" name="name<?php echo $i; ?>" value="<?php echo $row['prodname']; ?>" />
</td>
<td>
<?php echo $row['price']; ?>
<input type="hidden" name="price<?php echo $i; ?>" value="<?php echo $row['price']; ?>" />
</td>
<td><input name="quantity<?php echo $i; ?>" type="text" value="0"></td>
</tr>
<?php
$i++; //increment counter variable
}
?>
<input type="hidden" name="rows" id="rows" value="<?php echo $i; ?>" />
</table>
<br>
<input type="submit" value="Add Records">
</form>
Your insert page code goes here....
for($i=0;$i<=$_POST['rows'];$i++)
{
$prodid = $_POST['prod_id'.$i];
$pname = $_POST['name'.$i];
$pprice = $_POST['price'.$i];
$con ->exec("insert into product(prod_id,prodname,price)values('$prodid', '$pname','$pprice' )" );
}

I suggest putting the product_id in a hidden form element like this:
<tr>
<input type='hidden' name='product_id' value='<?php echo $row['product_id']; ?>'/>
<td><?php echo $row['product_id']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_price']; ?></td>
<td><input name="quantity" type="text" value="0"></td>
</tr>
This will send the product_id with your quantity and you can use it in your insert statement.
The only problem with this is if you have more than one row, there will be more than one hidden element for product_id, etc. Ways to overcome this include differentiating them by appending an incrementing number on the hidden element's name, e.g.:
$i = 1;
foreach ($results as $row)
{
$product_id_name = 'product_id_'.$i;
$quantity_name = 'quantity_'.$i;
... echo your table row, using $product_id_name in the hidden element, and $quantity_name in your text input
$i++;
}
Then in your inserting code you have to look for all the items in $_POST whose keys start with "quantity_", and if they are non-zero, get the integer NNN after the key prefix "quantity_", and get the corresponding product_id_NNN value to do your insert.

Related

Form send data to php with multiple inputs with the same name

I'm trying make a form where me or user can insert data. Some parts are coming form data base like: Work name and work price. In input fields can insert work amount. In each input row have checkbox, if checkbox ar checked, that row will be seen in php.
<table class="table">
<thead>
<tr>
<th scope="col">*</th>
<th scope="col">Work name</th>
<th scope="col">Quantity</th>
<th scope="col">Price for unit</th>
<th scope="col">Total price</th>
</tr>
</thead>
<form method="POST" action="process/pdf.process.php">
<tbody>
<?php
$works = ORM::for_table('work')->find_many();
foreach($works as $work){
?>
<tr id="<?php echo $work->id; ?>">
<td><input type="checkbox" name="useit[]" value="<?php echo $work->id; ?>"/></td>
<td><?php echo $work->name; ?></td>
<td><input type="text" placeholder="" class="amount"/> <?php echo $work->unit; ?></td>
<td class="work_price" data="<?php echo $work->price; ?>"><?php echo $work->price.'€/'.$work->unit; ?></td>
<td class="total_price">0€</td>
<input type="" name="work_id[]" value="<?php echo $work->id; ?>" />
<input type="hidden" name="work_name[]" value="<?php echo $work->name; ?>" />
<input type="hidden" name="amount[]" class="<?php echo $work->id; ?>_copy_amount" value="" />
<input type="hidden" name="unit[]" value="<?php echo $work->unit; ?>" />
<input type="hidden" name="unit_price[]" value="<?php echo $work->price; ?>€" />
<input type="hidden" name="unit_total[]" class="<?php echo $work->id; ?>_copy_total" value="" />
</tr>
<?php
}
?>
</tbody>
<input type="submit" name="do_pdf" value="Pga jkāuztaisa ar jquery" />
</form>
</table>
Now, there is php, but how can i show only checked rows in while loop?
<?php
$data = array();
$work_id = array();
$work_names = $_POST['work_name'];
$amounts = $_POST['amount'];
$units = $_POST['unit'];
$units_prices = $_POST['unit_price'];
$units_total = $_POST['unit_total'];
if(isset($_POST['useit'])){
$work_id = $_POST['useit'];
}
$data = array($work_id, $work_names, $amounts, $units, $units_prices, $units_total);
echo '<pre>';
echo htmlspecialchars(print_r($data, true));
echo '</pre>';
?>
There are different possibilities how to do that. One Suggestion (i limit it to the parts which are relevant)
form (note that i gave work_name the id as an index, use_it not (but it could have)
<td><input type="checkbox" name="useit[]" value="<?php echo $work->id; ?>"/></td>
<input type="hidden" name="work_name[<?php echo $work->id?>]" value="<?php echo $work->name; ?>" />
The form only submits the checked checkboxes values in an array, all other are omited. Therefore we could loop over the checked checkbox values like this
foreach($_POST['useit'] as $work_id){
$work_name = $work_names[$work_id];
//do something with the checked rows only (all others are not looped over)
}
This is only possible, due to the given id as an array key in the form work_name[<?php echo $work->id?>].
A general sidenote for better (and more secure) code: please note that your data could be modified by the user, and send back with wrong data (or worse). So please make sure to sanitize your input, or probably better in this case only submit the id in question and the new data and pickup the rest directly from your database. So you can make sure the hidden data has not been modified on the client side and send back wrong.

Checkboxes and multiple input array to database

I have read articles and questions regarding this issue but I'm still finding it difficult to go about it.
I'm trying to achieve course registration. So I have this table populated from my db.
<form method="post" action="courses.php">
<table>
<thead>
<th>Action<th>
<th>Course Title<th>
<th>Course Code<th>
<th>Course Unit<th>
</thead>
<tbody>
<!--Query that fetches the data from the db (included dbcon.php).. the courses are created by admin-->
<tr>
<td><input type="checkbox" name="isChecked[]" value="<?php echo $course_id?>"></td>
<td><input type="hidden" name="ctitle[]" value="<?php echo $title?>"> <?php echo $title?></td>
<td><input type="hidden" name="ccode[]" value="<?php echo $code?>"> <?php echo $code?></td>
<td><input type="hidden" name="cunit[]" value="<?php echo $unit?>"> <?php echo $unit?></td>
</tr>
</tbody>
</table>
<input type="submit" name="enroll">
</form>
If a checkbox is checked, How can I get all the values of the array (title, code, unit) and insert them on its corresponding column in my enroll table also note that the courses are more than 1?
here is the little I have done but I'm beginning to think that I'm not going to go through with it (imaging creating another foreach of the array? initializing a counter foreach??)
<?php
if(isset($_POST['enroll'])){
$i=0;
if(!empty ($_POST['isChecked'])){
foreach($_POST['isChecked'] as $course){
$course = $_POST['isChecked'][$i];
$query = "INSERT INTO enrolled (course_id)
VALUES ('$course')";
$insert = $db->query($query);
$i++;
}
}?>
The above insert the course id to my DB quite fine. But what I want is to actually insert all the data i.e (id, title, code, and unit to the database )
That is because your code is wrong. Try this:
<tr>
<td><input type="checkbox" name="isChecked['course_id']" value="<?php echo $course_id?>"></td>
<td><input type="hidden" name="isChecked['title']" value="<?php echo $title?>"> <?php echo $title?></td>
<td><input type="hidden" name="isChecked['code']" value="<?php echo $code?>"> <?php echo $code?></td>
<td><input type="hidden" name="isChecked['unit']" value="<?php echo $unit?>"> <?php echo $unit?></td>
</tr>
Do not forget to BIND your values and check them before to execute your SQL code.

Form action not allowing the delete of a record

I had to add a form action to go to a different page to edit a specific record, but with doing that, it won't allow me to delete a record because it is taking me away from it before it will do the query. I am unsure of how to make this work and still get to the new page when I hit the "Edit" button.
<table id="tableid">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Product</th>
<th>Save</th>
<th>Delete</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$stmt = $dbc->query("SELECT `id`,`first`,`last`,`product` FROM users");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
?>
<form method="POST" action="edit-product">
<tr>
<td><?php echo $row['id'];?>"</td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<input name="id" type="hidden" value="<?php echo $row['id'];?>" readonly>
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<td><input name="save" type="submit" value="Save"></td>
<td><div class="delete-class" name="delete" id="<?php echo $row['id']; ?>">Delete</div></td>
<td><input name="edit" type="submit" value="Edit"></td>
</tr>
</form>
<?php } ?>
</tbody>
</table>
PHP DELETE query
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
How can I change the markup to still get both the edit (going to another page with the action) and the delete to work on this page?
UPDATE AJAX code:
$(function() {
$(".delete_class").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete-product.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // DO SOMETHING
} else { // DO SOMETHING }
}
)); //here
});
});
This is not very ideal but one way to do it. You change the HTML markup to create two forms, one for edit case and another one for Delete. The delete case sends the request to the current page like this:
while($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<td>
<form method="post" action="edit-product">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<input name="save" type="submit" value="Edit">
</form>
</td>
<td>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="delete" type="submit" value="Delete">
</form>
</td>
</tr>
<?php }
?>
</tbody>
</table>
<?php
// the delete code goes here
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
I left out the save case but it will be similar to edit case.
Rather than having a form you could just have links instead of form submit buttons. That way each link could take you to a specific page that performs a specific task. By passing query string variables and using $_GET rather than $_POST, you can retain the product ID information.
Example:
<td>Save</td>
<td>Delete</td>
<td>Edit</td>
These individual pages could then perform your tasks in the database. Both save and delete could use Header re-directs to get back to your original page with your product list.
delete_product.php Example:
// delete product from database
$id = $_GET['id']; // Note that it's a $_GET
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
// re-direct to original list page
header("Location: product_list.php"); // or whatever you have your list page named.
The edit_product.php page would then have your typical form for making changes to a specific product. You will need to lookup the product again in the database using $_GET['id'] value to match it with.
As it was suggested in the comments, using AJAX would make the whole process appear to be seamless, rather than jumping around between pages and being re-directed.

Insert to database when the button is click

im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");

using PHP for each to get dynamic values from table

It's been a while since I looked at php and I've got a brain block. I'm trying to get the values from a table using foreach so that I can store the values in a session and also display the number of items that have been ordered.
eg 2 of item number 4 etc
here's the table / form
<form id="products" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
//every item from the products table is queried because all fields need to be displayed
$sSQL = "SELECT * FROM products";
$rsResult = mysql_query($sSQL);
?>
<table id="products_table">
<tr style="font-weight:bold">
<td style="text-align:center">ID</td>
<td>Ref No.</td>
<td>Product Name</td>
<td>Description</td>
<td style="text-align:right">Price</td>
<td colspan='2' style='text-align:center'>Add To Order</td>
</tr>
<!--for each record in the table that matches the query a row is created in the table and the data in the relevant field is displayed-->
<?php while ($row = mysql_fetch_array($rsResult)){ ?>
<tr>
<input type="hidden" name="productID[<? echo $row['productID']; ?>]" value="<? echo $row['productID']; ?>" />
<td style="text-align:center"><? echo $row['productID']; ?></td>
<td><? echo $row['productReference']; ?></td>
<td><? echo $row['productName']; ?></td>
<td><? echo $row['productDescription']; ?></td>
<td style="text-align:right"><? echo '£'. $row['productPrice']; ?></td>
<td style="text-align:center"><span>Qty</span><input type='text' name="qty[<? echo ($_POST['qty']); ?>]" value="" ></td>
<? } ?>
</table>
Heres the php
<?php
foreach($_POST as $key => $value){
echo $key . ' ' .$value.'<br />';
print_r($key);
}
?>
I know that the php is no where complete for filling sessions etc, I just can't work out how to get the values out of the form. This php was my attempt to try and at least get some kind of value out of it
Any help is greatly appreciated
in your code , there is no need of
<input type="hidden" name="productID[<? echo $row['productID']; ?>
field .
also change the line
<td style="text-align:center"><span>Qty</span><input type='text' name="qty[<? echo ($_POST['qty']); ?>]" value="" ></td>
to
<td style="text-align:center"><span>Qty</span><input type='text' name="qty[<? echo ($row['productID']); ?>]" value="" ></td>
so that after the submission of the form , you can access the posted values with :
$sSQL = "SELECT * FROM products";
$rsResult = mysql_query($sSQL);
while ($row = mysql_fetch_array($rsResult))
{
echo $_POST['qty'.$row['productID']];
}
why don't you just display data in inputs with proper names?

Categories