I am trying to update my cart quantity,my products are displayed with foreach loop .So, I tried to update it through this code , it worked but only for the first item selected on addtocart submit . What is the problem ? how to make the update for each item on one update button click ?
if (isset($_POST["quansub"]) ){
$itq = $_POST["itq"];
$_SESSION["itq"] = $itq;
$_SESSION["incart"][$select]["item_quantity"]= $_SESSION["itq"];
header("location:selecteditems.php");
}
Is this the sort of thing you want?
I would suggest for each item in your cart have something like this:
<input type='hidden' name='quantity[1]' id='quantity[1]'>
<input type='hidden' name='quantity[2]' id='quantity[2]'>
foreach($_POST['item'] AS $key=>$value){
$qty = $_POST["quantity"][$key];
$_SESSION["quantity"][$key] = $qty;
$_SESSION["incart"][$select]["item_quantity"]= $_SESSION["quantity"][$key];
}
Where you have "$select", use it to do the following:
<input type="text" name="itq[<?= $select ?>]" value="<?php echo $val["item_quantity"]; ?>"/>
Then do the following in PHP:
if (isset($_POST["quansub"] && $_POST['itq'][$select])){
$_SESSION["incart"][$select]["item_quantity"] = $_POST["itq"][$select];
}
Move this code outside of the foreach loop:
if (isset($_POST["quansub"])){
header("location:selecteditems.php");
}
Having "quantity[1], quantity[2]" etc... makes it very easy to loop through the input values and get out their values. This is very useful when storing multiple items into a database that are using the same names.
Giving the names a unique "key" also means you can determine where they belong to in a database as well as you could give them the "key" by using their database or product id for example.
If you want me to explain individual parts to this let me know.
Related
i am fetching different record from the database but using single quantity field trying to insert multiple records into MYSQL but every time for loop or any other loop overriding single value in all rows(inserting single first value in every field), badly stuck. kindly suggest what kind of appropriate steps should be done.
<input type="text" name="qty[]" id="qtyid" style="width:40px;">
<?php
if(isset($_POST["update"])) {
$usersCount=count($_POST['qty']);
$qtys=implode(",",$_POST['qty']);
for($i=0;$i<$usersCount;$i++) {
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
$total=$total*$qtys;
?>
Your "question" is unclear. I read it couple times nad i still dont know what is your problem.
Anyway. I'll try to explain what your code do in case it would help you to understand where the problem is.
//if form was submited and input of name "update" was in
if(isset($_POST["update"])) {
// count array created by inputs of name="qty[]"
$usersCount=count($_POST['qty']);
// make a string from that array, separating the keys by a "," char
$qtys=implode(",",$_POST['qty']);
// loop as many times as number of elements in that array = <input name="qty[]"> you had in submited form
for($i=0;$i<$usersCount;$i++) {
// and finally, do always the same for each loop repeat
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
So in conclusion your loop is doing always the same - every each repeat:
`$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";`
Basically to do that you would't need to have loop.
Because in that query you change value of column qty wherever column prodid is equal to something
I am building an application which has a dynamic table, everytime you open the page table`s row and columns changes based on data in database.
Each Row is a vendor company each colomn is a Item Title. All these vendors upply the same item, So this table has a textbox in each contains a TextBox so user can type the value, which represents the amount of fruit they want from that supplier. the following is the example.
So what I need to do now is, after entering these values, I'd like to process them through PHP, and then see 4 different reports at the confirm page, example: write the Company name and under that, what they have to supply for each item, then the next company, so on and so forth to the end.
I don't know if i should create different class for each textbox? or ID them!! SHould I Array them? I am confused.. If any of you guys can help, would be wonderful
Thanks a lot
I would suggest you just name the input elements as an array. something like:
<input type="text" name="fruits[company1][apple]">
<input type="text" name="fruits[company1][berries]">
<input type="text" name="fruits[company1][orange]">
<input type="text" name="fruits[company1][bannana]">
<input type="text" name="fruits[company2][apple]">
<input type="text" name="fruits[company2][berries]">
<input type="text" name="fruits[company2][orange]">
<input type="text" name="fruits[company2][bannana]">
or the same thing with the fruit being the first level and company name being second. It is really the same thing and generally just as easy to use either one. Just depends on how you want to loop over the data once you post the form. You might be better off also using ids for the company name and/or the fruit. Just makes it so, for example, company names with a space are still valid.
Using the above form, you can process the data with something like this:
<?php
foreach($_POST['fruits'] as $company=>$row){
foreach($row as $fruit=>$quantity){
if(!is_numeric($quantity) || $quantity < 0){
$quantity = 0;
}
echo "You selected {$quantity} {$fruit} from {$company}";
}
}
I would try creating a multi dim array with the ID of the item as the first dimension. Like this:
<input type="textbox" name="textbox[<?php echo $row['item_id']; ?>]["apple"]" value="<?php echo $row['apple']; ?>" />
Then, in your processing script:
foreach ($_POST['textbox'] as $row)
{
foreach ($row as $key => $val)
{
$q = "update `items` set `apple` = {$val['apple']} where `item_id` = {$key}";
mysql_query($q);
}
}
Im hoping someone can point me in the right direction of where im going wrong as I feel like im going around in circles!
Im putting together a simple shopping applications - its only very basic at the moment to demonstrate techniques.
The scenario is that there is one database table with items in. They have been split into a blue and red range of items.
On the index page the user has the option of going to either the blue or red items.
Once on the red (or blue) items page, items are displayed and current price and stock level is pulled from the database (MySQL). The user then selects one item and clicks the buy button to add it into their cart.
The page then redirects to the shopping cart page where the user can either update the quantity of the item, proceed to the checkout page or return to the 'red' or 'blue' ranges.
My issue is this.....
1) How do I set up my session array to capture the items as they are added on the buy 'click'?
So far I have this on the top of all pages...
<?php session_start();
?>
However only one item seems to be able to be added to the 'cart'.
This is how im pulling items from my DB:
<?php
$result = mysql_query ('SELECT * FROM items WHERE colour="red"');
// fetch the resulting row as an associative array
while ($row = mysql_fetch_assoc ($result)){
echo '£', number_format( $row ['price'] / 100, 2, '.', ' ' );
}
?></p>
2) This is the code for the form action under each item on either the red or blue page.
<form method="post" action="cart.php">
<p>
<input type="submit" name="submit" value="Buy" />
<input type="hidden" name="cart" value="add" />
<input type="hidden" name="item" value="redplate" />
</p>
</form>
3) How do I display the 'ordered' item in the checkout page after any quantity updates on the shopping cart page?
So far this is what it on the shopping cart page - would I repeat this on the checkout page pulling with it the updated quantity??....
<?php
$submit = $_POST["submit"];
//Call the function and save all data into the array $_SESSION['form']
if($submit == "Buy"){setSessionVars();}
function setSessionVars() {
$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
$item[$fieldname] = $fieldvalue;
}
$_SESSION['cart'] = $item;
echo " <table>
<tr>
<td>
<img src=\"images/{$item['item']}.jpg\" />
<td/>
<td>
{$item['item']} =
</td>
<td>
<input type=\"text(5)\" name=\"value\" value=\"1\" />
<input type=\"submit\" name=\"puchasedquan\" value=\"Click to update\" />
</td>
</tr>
</table>";
}
?>
Any help would be greatly appreciated!! I feel as if i'm traveling around in circles!
The problem with storing things in the PHP session vars is that they are stored in cookies, that means they require cookies to be turned on. Okay, most browsers have cookies set nowadays.
But how about if you read values directly from a client file, and put that into your database? Whats to stop someone from hacking the cookie file where it says "subtotal=10000" and changing the value to "subtotal=1", then push that through your system?
Your system would be more robust if you actually store the shopping session in your database, e.g.
CREATE TABLE tbl_shopping_session(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
php_session_key VARCHAR(32),
coupon_id INT,
FOREIGN KEY(coupon_id) REFERENCES tbl_coupons(id),
updated TIMESTAMP /* a timestamp is added to find & del old sessions */
) ENGINE = InnoDB;
CREATE TABLE tbl_shopping_cart(
shopping_session_id INT,
FOREIGN KEY(shopping_session_id) REFERENCES tbl_shopping_session(id) ON DELETE CASCADE,
product_id INT,
FOREIGN KEY(product_id) REFERENCES tbl_products(id),
cart_qty INT /* or DECIMAL(9,3) or something */,
subtotal DECIMAL(18,4)
) ENGINE = InnoDB;
From there on you could get the picture... the php_session_key is used to identify the current shopping session, and the current session id is used to find & store the cart items in a separate table.
The big mistake here is, you are putting all you datas on one session variable altogether, i.e. $_SESSION['cart'].
Since you want to insert multiple item on the sessions, you have use $_SESSION['cart'][] to insert the items.
Whenever you are trying to get the values stored, again use a for loop to read as well as .
foreach($_SESSION['cart'] as $cartItem) {
$cartItem; // will have all the item individually on each pass
}
try this
$item = array();
foreach($_POST as $fieldname => $fieldvalue) {
$item[$fieldname][] = $fieldvalue;
}
The $_SESSION keys are being replaced when you add more, so really it's just overwriting an existing value, you could add this:
foreach($_POST as $fieldname => $fieldvalue) {
// Now the array will be enumerated
$item[$fieldname][] = $fieldvalue;
}
print_r($item);
I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);
I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.