Post values of single row from while loop using onclick - php

I am trying to pass the column values from a single row generated from a while loop. When the link is clicked I want certain values from that row to be passed as hidden fields to another page.
The code:
<form id="repeat" name="repeat" action="edit_user.php" method="post">
<?php
$counter = 0;
while($row = $result->fetch_array()) {
$color = ($counter & 1)? "#D7ECEC" : "#DEDEDE";
$counter++;
?>
<tr align="left" valign="middle" style="background: <?php print $color; ?>">
<td><a href="#" onclick="document.getElementById('repeat').submit();" >
<?php echo $row['firstname']; ?> <?php echo $row['surname']; ?></a></td>
<td><?php echo $row['userlogin']; ?></td>
<td><?php echo $row['accesslvl']; ?></td>
<td ><?php echo $row['chgpasswrd']; ?></td>
</tr>
<input type="hidden" name="id" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="lvl" value="<?php echo $row['accesslvl']; ?>" />
<?php } ?>
</table>
</form>
What is happening is that the hidden fields are passing values for the last row of the while loop. Is it possible to do this so the hidden values being passed are from the same row of the link that is being clicked?
I've tried a few things and nothing works and I've not been able to find anything that directly relates to this problem. Any help would be appreciated. Cheers

You need to split this into two pages really. The first page displays the user info and link for each unique user, and the second page provides the edit form for posting the form data as follows...
<table>
<?php
$counter = 0;
while($row = $result->fetch_array()) {
$color = ($counter & 1)? "#D7ECEC" : "#DEDEDE";
$counter++;
?>
<tr align="left" valign="middle" style="background: <?php print $color; ?>">
<td>
<a href="edit_user.php?userID=<?php echo $row['userID']; ?>&accesslvl=<?php echo $row['accesslvl']; ?>">
<?php echo $row['firstname']; ?> <?php echo $row['surname']; ?>
</a>
</td>
<td><?php echo $row['userlogin']; ?></td>
<td><?php echo $row['accesslvl']; ?></td>
<td ><?php echo $row['chgpasswrd']; ?></td>
</tr>
<?php } ?>
</table>
on the edit_user page you can populate the hidden fields with the information passed in by the url query string. Remember to clean the values to prevent sql injection or xss attacks. I've used htmlentities here as an example and you may want to enhance this, read the php documentation page on htmlentites for more information (ENT_QUOTES).
$userID = htmlentities($_GET['userID']);
$accesslvl = htmlentities($_GET['accesslvl']);
<form action="modify_user.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$userID; ?>" />
<input type="hidden" name="lvl" value="<?php echo $accesslvl; ?>" />
//rest of form html

Related

How to delete specified row in a database table using post method in php

//Deleting is working. However, I can't delete the specified row in the table. It always deletes the last row. I hope you could help me. Thank you! This is my code for displaying data from database:
<form action="deleteCart.php" method = "post" role="form">
<?php
while ($row = mysqli_fetch_array($result2)) {
?>
<tr style="text-align: center;">
<td> <img src="images/<?php echo $row["ImageProduct1"]; ?>"/>
<td><?php echo $row['NameProduct1']; ?> </td>
<td>#<?php echo $row['OrderID']; ?></td>
<td><?php echo $row['OrderQuantity']; ?></td>
<td><input type="submit" name="cancelOrder" value = "Cancel" ></td>
<td><input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>"></td>
</tr>
<?php
}
?>
</form>
//This is my code for deleting:
if(isset($_POST['cancelOrder'])){
orderID = $_POST['hiddenID'];
mysqli_query($con, "DELETE FROM OrderTable WHERE OrderID=$_POST[hiddenID];");
header('location: deleteCart.php');
}
Delete only the last record because you submitting form whole table record. you should try this code. it will work fine.
this will submit separate record.
<?php
while ($row = mysqli_fetch_array($result2)) {
?>
<form action="deleteCart.php" method = "post" role="form">
<tr style="text-align: center;">
<td><img src="images/<?php echo $row["ImageProduct1"]; ?>"/>
<td><?php echo $row['NameProduct1']; ?> </td>
<td>#<?php echo $row['OrderID']; ?></td>
<td><?php echo $row['OrderQuantity']; ?></td>
<td>
<input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>">
<input type="submit" name="cancelOrder" value = "Cancel" >
</td>
</tr>
</form>
<?php
}
?>

GET single loop form data in hyperlink php

I am trying to update quantity as i fill the quantity field and click on update button. It works but it shows the form fields of each item in the loop and works for the last entry update only. Something like this.
/EcommerceClient/index.php?page=cart&action=update&id=3&name=%09%0D%0ACool+T-shirt&color=blue&size=XL&quantity=4&id=4&name=HBD+T-Shirt&color=yellow&size=XL&quantity=900
In the above link it should only get the information associated with id=3 only because i tried to update the quantity of id=3.
Here is my code. Any suggestions or help will be highly appreciated.
Code
if(isset($_GET['action']) && $_GET['action']=="update"){
$id= intval($_GET['id']);
$size = $_GET['size'];
$color = $_GET['color'];
$qty = $_GET['quantity'];
$index = $id." ".$color. " ".$size;
if( isset($_SESSION['cart'][$index]) && isset($_SESSION['cart'][$index]['color']) && $_SESSION['cart'][$index]['color'] == $color && isset($_SESSION['cart'][$index]['size']) && $_SESSION['cart'][$index]['size'] == $size){
$_SESSION['cart'][$index]['quantity']=$qty;
print_r($_SESSION['cart'][$index]);//It just shows me the last item array.
}
}
?>
<form class="product" method="get" action="index.php">
<table>
<input type="hidden" name="page" value="cart">
<input type="hidden" name="action" value="update">
<?php
if(isset($_SESSION['cart'])){
foreach($_SESSION['cart'] as $id => $value){
?>
<tr>
<input type="hidden" name="id" value="<?php echo $value['id'] ?>">
<input type="hidden" name="name" value="<?php echo $value['name'] ?>">
<input type="hidden" name="color" value="<?php echo $value['color'] ?>">
<input type="hidden" name="size" value="<?php echo $value['size'] ?>">
<td><?php echo $value['id'] ?></td>
<td><?php echo $value['name']?></td>
<td><?php echo $value['price']?> </td>
<td><?php echo $value['quantity']?><input type="text" name="quantity" value="<?php echo $value['quantity'] ?>"></td>
<td><?php echo $value['color'];?> </td>
<td><?php echo $value['size']; ?></td>
<td><?php echo "$" .$value['price']*$value['quantity']. ".00"; ?>
</tr>
<?php
}
}
?>
<tr><td><button type="submit">Update</button></td></tr>
</table>
</form>
You can update the quantity by not posting or getting all the cart product. Either you can use simple JS to update the field value or use SESSION variable array to update data as #Marc B mentioned.

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

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.

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?

Delete multiple rows mysql with checkbox

please help in deleting multiple rows from a table.
home.php
<form action="del.php" method="get" enctype="multipart/form-data">
<?php
while($row=mysql_fetch_array($rs))
{
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<?php echo $row['id']; ?>]" type="checkbox" id="checkbox[<?php echo $row['id']; ?>]" value="<?php echo $row['id']; ?>"></td>
<td><?php echo $row['listingtype'];?></td>
<td><?php echo $row['propertyname'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['listdate'];?></td>
</tr>
<?php
}
?>
</table>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr></form>
del.php
<?php
include "include/db.php";
$tbl_name='propertylistingbasicinfo';
// Check if delete button active, start this
if ( ! empty($_POST['delete'])) {
foreach ($_POST['need_delete'] as $id => $value) {
$sql = 'DELETE FROM `'.$tbl_name.'` WHERE `id`='.(int)$id;
mysql_query($sql);
}
header('Location: home.php');
}
?>
Error : When i click on delete button, blank screen come.
And url looks like this : http://localhost/realestate/del.php?need_delete%5B2%5D=2&delete=Delete
your mixing up GET with POST, change form method to post
You need something similar to this in your form
<input type="checkbox" name="record[]" value="<?php echo $id ?>">
then you can use implode() function to concatenate ids and remove them
$deleted = implode(',',$_POST['record']);
$query = mysql_query("delete from table where id in ('$deleted') ");
Not tested but this the idea.
The problem is that you are submitting the form with method="get" and in del.php, you are accessing values from $_POST. Change method="get" to method="post" on home.php
I would change it to the following...
home.php:
<form action="del.php" method="post" enctype="multipart/form-data">
<table>
<?php while($row=mysql_fetch_array($rs)) { ?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="need_delete[]" value="<?php echo $row['id']; ?>" type="checkbox" id="checkbox[<?php echo $row['id']; ?>]" />
</td>
<td><?php echo $row['listingtype'];?></td>
<td><?php echo $row['propertyname'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['listdate'];?></td>
</tr>
<?php } ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete" />
</td>
</tr>
</table>
del.php:
<?php
//Get the db-file and set the table name
include "include/db.php";
$tbl_name='propertylistingbasicinfo';
// Check if delete button active, start this
if ( !empty($_POST['delete'])) {
//Let's sanitize it
$sanitized_post_ids = array();
foreach($_POST['need_delete'] as $id ) $sanitized_post_ids[] = intval($id);
//Get the ids and add a trailing ",", but remove the last one
$in_str = substr(implode(',', $sanitized_post_ids), 0, -1);
//Build the sql and execute it
$sql = 'DELETE FROM ' . $tbl_name ' WHERE id IN (' . $in_str . ')';
mysql_query($sql);
//Redirect!
header('Location: home.php');
}
?>
Hope this works out for you (and that I didn't manage to add a typo or similar misshaps)!

Categories