using PHP for each to get dynamic values from table - php

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?

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

Echo Array into new lines

I have an edit page where a user can edit an invoice form. I need to echo the array into a table but separate each array into a new line on the table.
When i echo the value, its bunched up into one line. When i echo the value into an input field, i only get one record from the array.
Here's what it looks like in my table:
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$partnumber = $res['partnumber'];
$partdescription = $res['partdescription'];
$partprice = $res['partprice'];
$partquantity = $res['partquantity'];
}
>
And then the table:
<tr>
<td><input type="text" class="input-small" name="partnumber[]" value=<?php echo $partnumber;?>></td>
<td><input type="text" class="input-small" name="partdescription[]" value=<?php echo $partdescription;?>></td>
<td><input type="text" class="input-small" name="partprice[]" size="4" value=<?php echo $partprice;?>></td>
<td><input type="text" class="input-small" name="partquantity[]" size="4" value=<?php echo $partquantity;?>></td>
</tr>
I get this:
<tr>
<td><?php echo $partnumber;?></td>
<td><?php echo $partdescription;?></td>
<td><?php echo $partprice;?></td>
<td><?php echo $partquantity;?></td>
</tr>
I get this:
I tried the following but they both result in a blank echo:
<tr>
<td><? echo $res['partnumber']; ?></td>
</tr><tr>
<td><? echo $res['partdescription']; ?></td>
</tr><tr>
<td><? echo $res['partprice']; ?></td>
</tr><tr>
<td><? echo $res['partquantity']; ?></td>
</tr>
And
<? foreach ($res as $row) { ?>
<tr>
<td><? echo $row['partnumber']; ?></td>
<td><? echo $row['partdescription']; ?></td>
<td><? echo $row['partprice']; ?></td>
<td><? echo $row['partquantity']; ?></td>
</tr>
<?
}
?>
This is the GOAL:
Please help
EDIT***************
I will fix the security issue once i have the table working.
I tried this and the output is still on ONE line.
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE id='".mysql_real_escape_string($id)."' ");
while($res = mysqli_fetch_array($result))
{
?>
<tr>
<td><input type="text" class="input-small" name="partnumber[]" value=<?php echo $res['partnumber'];?>></td>
<td><input type="text" class="input-small" name="partdescription[]" value=<?php echo $res['partdescription'];?>></td>
<td><input type="text" class="input-small" name="partprice[]" size="4" value=<?php echo $res['partprice'];?>></td>
<td><input type="text" class="input-small" name="partquantity[]" size="4" value=<?php echo $res['partquantity'];?>></td>
<?php
}
?>
Does this help?
Please note, its only displaying 1 record because i have multiple values in one record and them i'm separating them with a comma. Please check screenshots above. Here's the code:
$partnumber = $_POST['partnumber'];
$partnumberarray = implode( ", ", $partnumber);
$partdescription = $_POST['partdescription'];
$partdescriptionarray = implode( ", ", $partdescription);
$partprice = $_POST['partprice'];
$partpricearray = implode( ", ", $partprice);
$partquantity = $_POST['partquantity'];
$partquantityarray = implode( ", ", $partquantity);
$result = mysqli_query($mysqli, "INSERT INTO invoicespartnumber, partdescription, partprice, partquantity, login_id) VALUES('$partnumberarray', '$partdescriptionarray', '$partpricearray', '$partquantityarray', '$loginId')");
Is there anyway i can echo the values from the 1 record which is separated by a comma into multiple lines on the table?
You have to put your html inside while loop that you do over result array.
It will look like this.
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE ID='".mysql_real_escape_string($id)."'");
while($res = mysqli_fetch_array($result)){ //close php here to easier write html. ?>
<tr>
<td><input type="text" class="input-small" name="partnumber[]" value="<?php echo $res['partnumber'];?>"></td>
<td><input type="text" class="input-small" name="partdescription[]" value="<?php echo $res['partdescription'];?>"></td>
<td><input type="text" class="input-small" name="partprice[]" size="4" value="<?php echo $res['partprice'];?>"></td>
<td><input type="text" class="input-small" name="partquantity[]" size="4" value="<?php echo $res['partquantity'];?>"></td>
</tr>
<?php //open php tag again to add end scope to while loop
}
?>
<table width = "100%">
<thead>
<tr>
// here will be all columns names in th
</tr>
</thead>
<tbody>
<?php
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM invoices WHERE id=$id");
while($res = mysqli_fetch_array($result))
{ ?>
<tr>
<td><?php echo $res['partnumber']; ?></td> <!-- Also use input box here -->
<td><?php echo $res['partdescription'];?><td>
<td><?php echo $res['partprice']; ?></td>
<td><?php echo $res['partquantity'];?></td>
</tr>
<?php
}
?>

update multiple rows in one sql query

Im new in php. this problem stuck me for two days. ergh. I want to display a table that contain input field so that user can insert the data and update it into database. User can change all the data in the table. I want to update multiple rows at a time, but it ends up updating only 1 row (the last row). Anyone please help me for this. Thnks.
This are the form.
This are the following code.
[<table>
<thead>
<tr>
<td><b>Item Code</b></td>
<td><b>Item Barcode</b></td>
<td><b>Item</b></td>
<td><b>QOH</b></td>
<td><b>Quantity</br>Checked</b></td>
<td><b>Quantity</br>Order</b></td>
</tr>
</thead>
<?php
$Barcode=$_SESSION\["Barcode"\];
$code=$_SESSION\["Code"\];
$itemcode=$_SESSION\["Itemcode"\];
$guid=$_SESSION\["guid"\];
$sql = "SELECT itemmastersupcode.*, itembarcode.*, stock_count_item.*, stock_count.*, po_ex_c.*, d.itemlink_total_qty
FROM itemmastersupcode
WHERE stock_count.SupCode = '$code' and stock_count_item.TRANS_GUID = '$guid'
GROUP BY itemmastersupcode.Itemcode";
$result=mysqli_query($conn2,$sql);
$rowcount = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result))
{
?>
<tbody>
<tr>
<td><?php echo $row\["Itemcode"\]; ?></td>
<td><?php echo $row\["Barcode"\]; ?></td>
<td><?php echo $row\["Description"\]; ?></td>
<td><?php echo $row\["itemlink_total_qty"\]; ?></td>
<td><?php echo $row\["qty"\]; ?></td>
<form class="form-inline" role="form" method="POST" id="myForm">
<td><input type="number" name="qty" value=""/></td>
</tr>
</tbody>
<input type="hidden" name="itemcode" value="<?php echo $row\["itemcode"\]; ?>"/>
<input type="hidden" name="supcode" value="<?php echo $_SESSION\["Code"\] ?>"/>
<input type="hidden" name="guid" value="<?php echo $_SESSION\["guid"\] ?>"/>
<?php
}
?>
</table>
<button name="save" type="submit" ><b>SUBMIT</b></button>
</form>
<?php
if (isset($_POST\["save"\]))
{
$itemcode=$_POST\['itemcode'\];
$qty=$_POST\['qty'\];
$supcode=$_POST\['supcode'\];
$guid=$_POST\['guid'\];
$sql = "UPDATE stock_count, stock_count_item SET stock_count.posted = '1', stock_count_item.qty_order = '$qty'
WHERE stock_count.TRANS_GUID = '$guid' AND stock_count_item.Itemcode ='$itemcode'
and stock_count_item.TRANS_GUID = '$guid' ";][1]
An UPDATE query will update all records that are filtered by the WHERE clause. If no WHERE is given, all records are updated:
UPDATE table1 SET field1='value1';
will set the field1 column of all records to value1.
UPDATE table1 SET field1='value1' WHERE field2='value2';
will set the field1 column to value1 or all records where field2 is equal to value2.
So, in your case, the records that are found through the WHERE clause are updated. This is all basic SQL stuff by the way, so I advise you to read up on SQL.
Finally, also use prepared statements in your code to prevent SQL injection.
<table>
<thead>
<tr>
<td><b>Item Code</b></td>
<td><b>Item Barcode</b></td>
<td><b>Item</b></td>
<td><b>QOH</b></td>
<td><b>Quantity</br>Checked</b></td>
<td><b>Quantity</br>Order</b></td>
</tr>
</thead>
<?php
$Barcode=$_SESSION["Barcode"];
$code=$_SESSION["Code"];
$itemcode=$_SESSION["Itemcode"];
$guid=$_SESSION["guid"];
$sql = "SELECT itemmastersupcode.*, itembarcode.*, stock_count_item.*, stock_count.*, po_ex_c.*, d.itemlink_total_qty
FROM itemmastersupcode
WHERE stock_count.SupCode = '$code' and stock_count_item.TRANS_GUID = '$guid'
GROUP BY itemmastersupcode.Itemcode";
$result=mysqli_query($conn2,$sql);
$rowcount = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result))
{
?>
<tbody>
<tr>
<td><?php echo $row["Itemcode"]; ?></td>
<td><?php echo $row["Barcode"]; ?></td>
<td><?php echo $row["Description"]; ?></td>
<td><?php echo $row["itemlink_total_qty"]; ?></td>
<td><?php echo $row["qty"]; ?></td>
<form class="form-inline" role="form" method="POST" id="myForm">
<td><input type="number" name="itemcode[<?php echo $row["itemcode"]; ?>][qty]" value=""/></td> //update here
</tr>
</tbody>
<?php
}
?>
</table>
<input type="hidden" name="supcode" value="<?php echo $_SESSION["Code"] ?>"/> //update here
<input type="hidden" name="guid" value="<?php echo $_SESSION["guid"] ?>"/>//update here
<button name="save" type="submit" ><b>SUBMIT</b></button>
</form>
Php content
<?php
if (isset($_POST["save"]))
{
$itemcodes=$_POST['itemcode'];
$qty=$_POST['qty'];
$supcode=$_POST['supcode'];
$guid=$_POST['guid'];
$sql = "UPDATE stock_count, stock_count_item SET
stock_count.posted = '1',
stock_count_item.qty_order = CASE stock_count_item.Itemcode";
foreach( $itemcodes as $itmcode=>$qty)
{
$sql.=" WHEN ".$itmcode." THEN ".$qty
}
$sql.=" END WHERE stock_count.TRANS_GUID =$guid AND stock_count_item.TRANS_GUID=$guid AND stock_count_item.Itemcode IN (".implode(",",array_keys( $itemcodes)).") ";
?>
Hope it will help

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.

display the content of table in checkbox form

I have a table called "project_name" in my database called "encrypt_decrypt". The table contains only 1 column called "name" which contains different values of name (ex : p1, p2, p3...). I have to retrieve this values(p1,p2,p3..) from my database and display it on a registration form with each value displaying one below the other having a checkbox with it so that user can select any of the name while registering! How do i do this in php ???
Thanks in advance!
<html>
<body>
<form name="reg" action="code_exec2.php" onsubmit="return validateForm()" method="post">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td><div align="right" style="white-space:nowrap" >Please select the project:</td>
</tr>
<tr>
<td><div align="right"><input type="checkbox" name="project[]" ></div></td>
<td><?php
session_start();
include('connection2.php');
$row=mysql_query("select * from project_name");
$array= array();
$output = mysql_fetch_assoc($row);
while($output){
$array[] = $output;
}
print_r($array);
?></td>
</tr>
<tr>
<td><div align="right"><input type="checkbox" name="Select all"
value="select all" onclick="toggle(this)"></div></td>
<td>Select all</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
Try this.
$result=mysql_query("select * from project_name");
$checkboxes=array();
while($r=mysql_fetch_assoc($result)){
$checkboxes[]='<input type="checkbox" name="names[]" value="'.$r['name'].'">'.$r['name'].'<br />';
}
Then echo below wherever you want the checkboxes to appear.
echo implode("\n",$checkboxes);
Assuming, that your connection to db is correct, you need to change the way you display results:
<?php
session_start();
include('connection2.php');
$row=mysql_query("select * from project_name");
$array= array();
while($output = mysql_fetch_assoc($row)){
//now you have row with name, and you need to display each name with new tr:
?>
<tr>
<td><div align="right"><input type="checkbox" name="project[]" value="<?php echo $output['name'] ?>"></div></td>
<td><?php echo $output['name'] ?></td>
</tr>
<?php } // closing while loop
?>
Note that I added value to checkbox - if you want to do something with checked project, you have to know which one it was.
And remember taht mysql_ functions are depreated! You should use PDO or mysqli_ instead
i tried this and i got: any ways thanks for all your help :)
<?php
include('connection.php');
$r=mysql_query("select distinct name from project_name");
$ProdArray=array();
while ($row = mysql_fetch_object($r)) {
array_push($ProdArray,$row->name);
}
foreach($ProdArray as $p) {
echo "<tr>";
echo "<td><div align='right'>";
echo "<input type='checkbox' name='project[]' value=" .$p. " />";
echo "</div></td>";
echo "<td>$p</td>";
echo "</tr>";
}
?>

Categories