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
Related
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.
I have a html form which displays the contents of a mySQL table called banner, containg multiple banner elements, that appear like:
Im using PHP Codeigniter. I want users to be able to update the display checkbox and submit, storing the values 1 and 0 in the database for checked / not.
FormView
<td>
<input type="checkbox" name="bdisplay[]" value="<?php $bannerId?>" <?php if ($displaycheck==1): ?> checked <?php endif;?>>
<?php echo $banner->bdisplay; ?>
</td>
The function for form submission. It creates a new associative array, if checkbox ticked id=>1 or else id=>0.
public function do_updatedisp()
{
$results = array();
foreach($_POST['bdisplay'] as $onedisplay)
{
if(!empty($onedisplay))
{
array_push($results, $results[$onedisplay]=1);
}
else
{
array_push($results, $results[$onedisplay]=0);
}
$this->bannerM->form_update($results);
}
}
The banner model:
function form_update($results)
{
foreach($results as $result=>$value)
{
$this->db->set('bdisplay', $value);
$this->db->where('banner_id', $result);
$this->db->insert('banner');
}
}
This is the error I get:
Cannot add or update a child row: a foreign key constraint fails (vigilantx.banner, CONSTRAINT FK__usarios FOREIGN KEY (user_id) REFERENCES usarios (user_id))
I know there is nothing wrong with the foreign key, there is error elsewhere but
I have been stuck on this for far too long! Any help appreciated!
i'm not sure but i think the problem is the insert method because everytime a user clicks on this checkbox he inserts a new row to your table which could be problematic (don't know your db schema but i think thats causing the foreign key troubles)
try this instead
function form_update($results)
{
foreach($results as $result=>$value)
{
$this->db->set('bdisplay', $value);
$this->db->where('banner_id', $result);
$this->db->update('banner');
}
}
I guess you are making things a big complicated for yourself, you are doing things correctly but doing too much. Basically the value you have implemented the form is correct, for instance you form with checkbox
display banner
when a form is submitted irrespective of any HTTP method being used, on server side only set values are passed therefore on php side if the checkbox is not checked then it will not be present to PHP runtime therefore if you simply check.
<?php
// using HTTP get method
// default value for banner display is zero
$banner_display = 0;
if(isset($_GET['bdisplay'])
$banner_display = 1;
// further write code to do whatever processing you would like to do
?>
The above code works in case you simply have a single checkbox which is optional to user furthermore using just if statement is a optimal way of writing code which help in generating extra branching instructions
Please see this link
http://thedesigningworld.com/bea
Here's a Small form contains 8-9 fields + a group of checkboxes
I want to save all details in DB + want to display in a table in proper manner, but it not works properly
Here's the code which i used
for($i=0;$i<count($_POST[wert1]);$i++)
{
if($_POST[wert1][$i]!= "")
{
$check1[] =$_POST['wert1'][$i]; } }
$new1=implode(',', $check1);
$result = "INSERT into table1(check1) values($new1)";
$result = mysqli_query($con, $result);
So i've one doubt that for each checkbox row, should i need to define same array name or different like here i used array name as wert1[] for first row
Checkbox values are not transmitted if the box is not checked.
If you have influence, you could put a hidden input field of the same name before the checkbox and the value "0", like:
<input type="hidden" name="checkbox_name" value="0" />
<input type="checkbox" name="checkbox_name" value="1">Some Text</input>
In you example site, you're using array notation, which is basically a good thing. However, you have not given an index so you might not recognize missing elements.
okay, im new in this site also new in php and can't get the logic on this,
i have a product page that shows the name, quantity and an add to cart button in each row of product
i made this just cutted of some code
while($showProducts = mysql_fetch_array($products))
{
$currenQuantity = $showProducts['current_quantity'];
$prodid = $showProducts['product_id'];
echo"<select name='quan'>";
for ($x=0;$x<=$currenQuantity;$x++)
{
if($currenQuantity != 0)
{
echo "<option value=$x> $x </option>";
}
}
echo"</select><br/>";
}
now the problem is every time i tried to get the value by using $_POST['quan'] the value that i always get is the default value 1 even i select a different value of quantity of a certain product, and i'm blanked with ideas.
You can't use the same name for an input/select field in a form.
You have to specify a diffrent name or create an indexed array:
<select name="quan[$prodid]">
You can acces it via
$_POST['quan'][$prodid]
Just a wild guess: has each of your product rows a select named 'quan'?
Then you're getting the last select named 'quan' in your POST data.
Prefix each of the quantities selects with name of the product, or some kind of a (scrambled) id.
Additionally:
If you don't want to have a 0 in your select, don't start the for loop with 0
for ($x=1;$x<=$currenQuantity;$x++)
if the current quantity is 0, the for loop doesn't get executed.
If you have more selectboxes with the same name (quan) in one form, you are getting value of the last one.
You should change the selectbox definition to:
echo"<select name='quan[" . $prodid . "]'>";
then you can access the values using:
$_POST["quan"][$some_product_id]
$_POST["quan"][$another_product_id]
I've just started using jQuery. One thing I've been using it for is adding rows to a table that is part of a form.
When I add a new row, I give all the form elements names like 'name_' + rowNumber. I increment rowNumber each time I add a row.
I also usually have a Remove Row Button. Even when a row is removed, the rowNumber count stays the same to keep from repeating element names.
When the form is submitted, I set a hidden element to equal the rowNumber value from jQuery. Then in PHP, I count from 1 to the rowNumber value. Then for each value, I perform an isset($_REQUEST['name'_ . index]). This is how I extract the form elements that remained after deleting rows in jQuery.
Does anyone here have a better technique for accounting for deleted rows?
For some of our simpler tables, we use a field name such as 'name[]', though for JavaScript they would need a usable id.
It does add some complexity in that 'name[0]' has to assume 'detail[0]' is the correct element.
PHP will create an array and append elements if the field name ends with [] similar to
<input name="field[]" value="first value" />
<input name="field[]" value="second value" />
// is roughly the same as
$_POST['field'][] = 'first value';
$_POST['field'][] = 'second value';
Use arrays to hold you values in your submission. So bin the row count at the client side, and name your new elements like name[]. This means that $_POST['name'] will be an array.
That way at the server side you can easily get the row count (if you need it) with:
$rowcount = count($_POST['name']);
...and you can loop through the rows at the server side like this:
for ($i = 0; isset($_POST['name'][$i]; $i++) {}
You could extract all the rows by doing a foreach($_POST as $key => $value).
When adding a dynamic form element use the array naming method. for example
<input type="text" name="textfield[]" />
When the form is posted the textfield[] will be a PHP array, you can use it easily then.
When you remove an element make sure its removed from the HTML DOM.
Like blejzz suggests, I think if you use $_GET, then you can just cycle through all of the inputs that were sent, ignoring the deleted rows.
foreach ($_GET as $k=>$v) {
echo "KEY: ".$k."; VALUE: ".$v."<BR>";
}
I notice that you mention "accounting for deleted rows"; you could include a hidden input, and add a unique value to it each time someone deletes a row. For example, the input could hold comma-separated values of the row numbers:
<input type="hidden" value="3,5,8" id="deletions" />
and include in your jQuery script:
$('.delete').click(function(){
var num = //whatever your method for getting the row number
var v = $('#deletions').val();
v = v.split(',');
v.push(num);
v = v.join(',');
$('#deletions').val(v);
});
Then you should be able to know which rows were deleted (if that is what you were looking for).
you can use POST or GET
After submit you can use all of your form element with this automaticly. You dont need to reorganise your form element names. Even you dont need to know form elements names.
<form method="POST" id="fr" name="fr">.....</form>
<?php
if(isset($_POST['fr'])){
foreach($_POST as $data){
echo $data;
}
}
?>
Also you should look this
grafanimasyon.blogspot.com.tr/2015/02/veritabanndan-php-form-olusturucu.html
This is a automated form creator calcutating your database tables. You can see how to give name to form elements and use them.