Jump to content

Storing array values from form


mallen
 Share

Go to solution Solved by mallen,

Recommended Posts

I have an array of products with categories they appear in. This gets stored in a category assoc table. When I edit a product listing, it get the last id, makes an entry with the table using assoc id, product id, cat id. But I am loosing the product order. Is it possible to store the product order value the same time I store the category id? Currently it just records "0" for the order. I need the value of the order in the loop.

$cats = $prod->getProductCategories();
		if(count($cats)>0)
				{
				
		foreach($cats as $cat)
		{
		?>
		<tr>
		<td><?php echo $cat['cat_name'];?></td>
		<td><input type='checkbox' name='prodCategories[]' value='<?php echo $cat['cat_id']; ?>' <?php if($editProduct) echo $prod->isCheckSelected($cat['cat_id'], $vals['prod_id']);?>/>
						
		<input type="text" name='prodCategories[][order]' value="79" />
		</td>
		</tr>
		<?php
					
			}
		}

//on my product class...
			for($i= 0; $i < count($cats); $i++)

			{

			$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order) VALUES('$lastID',' ". $cats[$i] . "','". $order[$i] . "')";
			$wpdb->query($catCategory);
		
	}
Link to comment
Share on other sites

rather than posting code that doesn't work, which doesn't tell us what your data actually looks like, what processing you are trying to do on that data, and what result you are trying to produce, sit down and define as much as you can, first, then design and write the code and queries that implement each part of the task.

 

1) what is the overall goal you are trying to achieve, i.e. what is the name of this task/process? are you trying to just edit existing product data (remove existing categories and edit the custom order) or are you also trying to add new categories (for both products that have no existing data and ones that do), along with removing existing categories and editing the custom order? are you going to do this for one product at a time or multiple products at the same time?

 

2) what input data is needed to accomplish this task? this will define what data the form needs when it is built, what it needs to submit to the form processing code, and how it will be structured.

 

3) what processing are you going to do based on the input data or combinations of the input data? for just editing existing data, what happens if a check-box is un-checked? should this cause the matching row to be deleted and also ignore any submitted custom order data?

 

4) what result are you going to produce or output? insert new rows? update existing rows? what error or success messages will there be?

 

note: if you are faced with inserting new data or updating existing data, often an INSERT ... ON DUPLICATE KEY UPDATE ... query will come in handy.

 

after you define these things, writing the code/queries will be easy and if you need to ask us a question, it will provide us with the information we would need to help you.

 

you also need to use a prepared query, with place-holders in the sql statement for data values, then supply the actual data when the query is executed. you can research in the php.net documentation or on the web to find out what this means.

Edited by mac_gyver
Link to comment
Share on other sites

Ok getting closer.

For every category that is listed with a check mark I show the "order" of the the product I am editing. i.e. The product is number "2" means it appears 2nd that category. If I have multiple categories posting it is only holding and storing a singe value. The rest are showing "0" and they should be their respective placement order number.

 

Imagine a vertical list of categories with check boxes and some are checked with hidden values. Like "2" as described above.

 

To simplify it, I am only showing the three sections of code where I get the value posted, then loop, and then insert to the database.

 

Listing and showing the categories and check marks and values WORKS.

What DOESN'T work is storing each value. The ' p_order' is always "0" for all entries.


The FORM -----------------------------------------------------------------

$cats = $prod->getProductCategories();
                if(count($cats)>0)
                {
                
                    foreach($cats as $cat)
                    {
                        ?>
                        <tr>
                        <td><?php echo $cat['cat_name'];?></td>
                        <td><input type='checkbox' name='prodCategories[]' value='<?php echo $cat['cat_id']; ?>' <?php if($editProduct) echo $prod->isCheckSelected($cat['cat_id'], $vals['prod_id']);?>/>
                        <?php if($editProduct) echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']); ?>
                        
                        <input type='hidden' name='orderp[]' value='<?php echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']);?>' />
                        </td>
                        </tr>
                        <?php
                    
                    }
                }                


The VALUES------------------------------------------------------------------------------

$cats = $_REQUEST['prodCategories'];
$orderp = $_REQUEST['orderp'];
        
	

The INSERT-------------------------------------------------------------------


$wpdb->query("DELETE FROM category_assoc WHERE prod_id = '$lastID'");
       

	for($i= 0; $i < count($cats); $i++)

	{

		$thecatx = $cats[$i];
		$orderx = $orderp[$i];

		$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order) VALUES ('$lastID', '$thecatx', '$orderx')";
		
		$wpdb->query($catCategory);
		
	}



Edited by mallen
Link to comment
Share on other sites

<tr>
<td>USA Guitars</td>
<td><input type='checkbox' name='prodCategories[]' value='3' checked/>
												
<input type="hidden" name="orderp[]" value='2'/>
</td>
</tr>
<tr>
<td>Guitars</td>
<td><input type='checkbox' name='prodCategories[]' value='36' checked />
												
<input type="hidden" name="orderp[]" value='5'/>
</td>
</tr>





So for example the product I am editing shows in position "2" in the USA Guitars category and position "5" in the Guitars category

Link to comment
Share on other sites

Have you tried printing the values of $orderp and $orderx before running the query?
Does it actually have the values 2 and 5 ?

<?php

$orderp = $_REQUEST['orderp'];
print_r($orderp); // this should print an array with values 2 and 5

for($i= 0; $i < count($cats); $i++) {
	$orderx = $orderp[$i];
	echo $orderx; // this should echo the values 2 and 5
}

?>
Link to comment
Share on other sites

Checkbox values are only sent if the box is checked. I think the problem you're having is that the checkbox array is (33,50) for the two boxes checked (for example) while the hidden elements are coming across as (1,2,3,4,5). Now cat[x] and orderp[x] do not align.

 

I would build your form with explicit keys in the element names. prodcat[0], prodcat[1], etc. instead of just []. Then you'll have cat(2=>33,4=>50) and orderp(1,2,3,4,5) where cat[2] and orderp[2] are now aligned. You can use a foreach() to loop through the cat[] values, find orderp[$key] corresponding to it, and then build your query.

Link to comment
Share on other sites

<tr>
<td>USA Guitars</td>
<td><input type='checkbox' name='prodCategories[]' value='3' checked/>
												
<input type="hidden" name="orderp[]" value='2'/>
</td>
</tr>
<tr>
<td>Guitars</td>
<td><input type='checkbox' name='prodCategories[]' value='36' checked />
												
<input type="hidden" name="orderp[]" value='5'/>
</td>
</tr>
Given that code, for example, with only the second checkbox checked, you'll have

 

$_REQUEST['prodCategories'] = array(36)

and

$_REQUEST['orderp'] = array(2,5)

 

there's no way to relate $_REQUEST['prodCategories'][0] to $_REQUEST['orderp'][1], which is what I assume you want.

 

Create your code like this, instead:

<tr>
<td>USA Guitars</td>
<td><input type='checkbox' name='prodCategories[0]' value='3' checked/>
												
<input type="hidden" name="orderp[0]" value='2'/>
</td>
</tr>
<tr>
<td>Guitars</td>
<td><input type='checkbox' name='prodCategories[1]' value='36' checked />
												
<input type="hidden" name="orderp[1]" value='5'/>
</td>
</tr>
And now you have

 

$_REQUEST['prodCategories'] = array(1=>36)

and

$_REQUEST['orderp'] = array(0=>2,1=>5)

 

where $_REQUEST['prodCategories'][1] and $_REQUEST['orderp'][1] are now related elements.

Link to comment
Share on other sites

Thanks. I think this was the problem. So to get those results....name='prodCategories[1]'    I would need to change this part?

foreach($cats as $cat)//original

for($i= 0; $i < count($cats); $i++)//change


<input type='checkbox' name='prodCategories[] (not sure) 

Edited by mallen
Link to comment
Share on other sites

That would work, but you'd have to change how you reference $cat inside the for() loop.

 

Or you could just keep a counter and output it's value in the prodCategories[] and orderp[] brackets, like below:

 

$i = 0;
foreach($cats as $cat) { ?>
  <tr>
    <td><?php echo $cat['cat_name'];?></td>
    <td>
      <input type='checkbox' name='prodCategories[<?=$i?>]' value='<?php echo $cat['cat_id']; ?>' <?php if($editProduct) echo $prod->isCheckSelected($cat['cat_id'], $vals['prod_id']);?>/>
      <?php if($editProduct) echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']); ?>                  
      <input type='hidden' name='orderp[<?=$i++?>]' value='<?php echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']);?>' />
    </td>
  </tr>
<?php
}
Link to comment
Share on other sites

I tried that but it looped and made all the categories have a 'orderp' even if they weren't checked. I changed it to this since I had the IDs and order. But when it posts it sends the "orderp' and 'cat_id' but it wiped them out and doesn't save. when it was prodCategories[]  without a number it would save on entry.

<tr>
	<td><?php echo $cat['cat_name'];?></td>
	<td><input type='checkbox' name='prodCategories[<?php echo $cat['cat_id'];?>]' value='<?php echo $cat['cat_id']; ?>' <?php if($editProduct) echo $prod->isCheckSelected($cat['cat_id'], $vals['prod_id']);?>/>
	<?php if($editProduct) echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']);//ADDED GETS ORDER OF ITEM ?>
						
	<input type="hidden" name="orderp[<?php echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']);?>]" value='<?php echo $prod->gettheOrder($cat['cat_id'], $vals['prod_id']);?>'/>
	</td>
	</tr>
<tr>
<td>USA Guitars</td>
<td><input type='checkbox' name='prodCategories[0]' value='3' checked/>
												
<input type="hidden" name="orderp[0]" value='2'/>
</td>
</tr>
<tr>
<td>Guitars</td>
<td><input type='checkbox' name='prodCategories[1]' value='36' checked />
												
<input type="hidden" name="orderp[1]" value='5'/>
</td>
</tr>
Edited by mallen
Link to comment
Share on other sites

You also have to change how you loop through the results. The key of prodCategories and orderp being the same is what links them.

 

I think like this...

	foreach($cats as $i=>$thecatx) 

	{

		//$thecatx = $cats[$i];
		$orderx = $orderp[$i];

		$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order) VALUES ('$lastID', '$thecatx', '$orderx')";
		
		$wpdb->query($catCategory);
		
	}
Link to comment
Share on other sites

Also to clarify the order is where that product appears in that category. Not the order of the categories. Below it would appear in position 2 and position 5

<tr>
<td>USA Guitars</td>
<td><input type='checkbox' name='prodCategories[3]' value='3' checked/>
												
<input type="hidden" name="orderp[2]" value='2'/>
</td>
</tr>
<tr>
<td>Guitars</td>
<td><input type='checkbox' name='prodCategories[1]' value='1' checked />
												
<input type="hidden" name="orderp[5]" value='5'/>
</td>
</tr>
Link to comment
Share on other sites

I don't think that's what you want.

 

Walk me through the sequence here. When I check "USA Guitars" which as a category of "3", you also want to know that the orderp value relating to USA Guitars/category 3 is "2", right?

 

And when you build your query, you want to know that category 3 has an orderp value of 2, right?

 

If you used your above code, and checked the second checkbox for "Guitars" category "1", you'd have the following two arrays in $_POST or $_REQUEST:

 

['prodCategories'] = array(3=>'3')

['orderp'] = array(2=>'2', 5=>'5')

Link to comment
Share on other sites

I dumped my categories and I think I know the issue. prodCategories is an array but I don't think porder is being saved and sent as an array. But if I leave it as name='prodCategories[]' it will save the first category with its correct orderp.

3 => 
   
      'cat_id' => string '3'
      'cat_name' => string 'USA Guitars'
      'cat_order' => string '41'
      
4 => 
   
      'cat_id' => string '1'
      'cat_name' => string 'Guitars'
      'cat_order' => string '41'
     
Edited by mallen
Link to comment
Share on other sites

before trying a bunch more things, you need to define exactly what overall goal you are trying to accomplish (see my 1st post in this thread.)

 

by this, i don't mean, stating or showing what action you are trying to make work. inserting data is an action. this action is not what you are trying to accomplish.

 

your statement in post #3 in the thread doesn't clarify anything. what exactly are you 'editing'? are you editing the custom order values? are you deleting entries where the check-box is not checked?

 

what exactly do you want to happen if a check-box is checked for a row of data? what exactly do you want to happen if a check-box was check, but is no longer checked?

 

if you are editing the custom order values, why are you using a hidden field? if your current code 'worked', you would be inserting exactly the same custom order data that you already have. if you are editing the custom order values, you would display the current value and allow them to be changed to new values.

Link to comment
Share on other sites

The order of the products is done elsewhere.

I am loosing the relation of the product's order in realtion to its category. When I edit names, descriptions ect. it creates a new assoc_id and enters the data below. That is where I loose the saved data that was there. The categories the product appears in holds ok. Just looses that "p_order". So if product 1 appears in cat 8, 3, and 6 the table would show:

842, 8, 45

843, 3,10

844, 6, 66

 

but I loose it and it looks like this:

845,8, 0

846,3,0

847,6, 0

$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order) VALUES('$lastID',' ". $cats[$i] . "','". $order[$i] . "')";
Edited by mallen
Link to comment
Share on other sites

Correct. But I am not changing the order or the category association. Its large page with lots of files, descriptions, model numbers etc. So if a category has 50 products and a custom order I want to retain that. maybe I eed to merge the two?

prodCategories[]

orderp[]

Edited by mallen
Link to comment
Share on other sites

Thanks again for all your help. I revised my approach. I was able to combine my two arrays of the category and the order each product appears in each category. Now I am working on the insert. Still losing the value of "p_order"

Array data
----------------------------------------------------------
0 => 
    
      'prod_id' => string '184'
      'cat_id' => string '3'
      'p_order' => string '5'
      
      
1 => 
    
      'prod_id' => string '174'
      'cat_id' => string '9'
      'p_order' => string '21'
 
      
      
    Form  
    ------------------------------------------------------  
      
      
      foreach($combined as $together)
					
	{
	?>
	<tr>
	<td><?php echo $together['cat_name'];?></td>
	<td><input type='checkbox' name='together[]' value='<?php echo $together['cat_id']; ?>' <?php if($editProduct) echo $prod->isCheckSelected($together['cat_id'], $vals['prod_id']);?>/>
						
	</td>
	</tr>
						
						
	Product class					
	------------------------------------------------------					
						
	
	$together = $_REQUEST['together'];
	for($i= 0; $i < count($together); $i++)	

	
	
	{
		

		$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order) 
		VALUES('$lastID', '". $together[$i]."','". $together['p_order'] . "')";
		
		

		$wpdb->query($catCategory);
		
      
Link to comment
Share on other sites

your current form data doesn't have any p_order values or field name in it, so, i'm wondering how you would expect your code to have any input data upon which to operate.

 

i'll state it once more, if you are editing the product names, descriptions ect, the data in the category_assoc table does not change.

 

you will only be changing the data in the category_assoc table if you are adding or removing categories for a product or changing the custom order for a product. since you have stated you are performing these actions elsewhere, the code you have been trying to make work in this thread doesn't have anything to do with the stated task of editing product names, descriptions, ...and isn't needed.

 

if you are editing product names, descriptions, ... the only thing you should be doing is executing an UPDATE query against the table holding the product product names, descriptions, ...

 

if you are doing something else, you have not provided any information upon which to help you. 

Link to comment
Share on other sites

$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order)

VALUES('$lastID', '". $together[$i]."','". $together['p_order'] . "')";

$together['p_order'] doesn't make any sense, notwithstanding that there's no p_order element in your form, as mentioned.

 

Can you post a var_dump() of $_REQUEST once you've submitted this form, with some boxes checked and others not checked? An actual copy/paste of the generated HTML form would be helpful, too.

Link to comment
Share on other sites

I still think this is a naming issue with being able to relate a checkbox to a text box.

 

Consider this. I created a form that asks for a Name, Age and has a checkbox on whether that person should be validated. I supplied four names, four ages and clicked validate on two of the names. With the below dump of the $_POST data, can you tell me what two names I checked?

 

array(3) {
  ["name"]=>
  array(4) {
    [0]=>
    string(4) "John"
    [1]=>
    string(5) "Roger"
    [2]=>
    string(7) "Rebecca"
    [3]=>
    string(5) "Bobby"
  }
  ["age"]=>
  array(4) {
    [0]=>
    string(2) "29"
    [1]=>
    string(2) "33"
    [2]=>
    string(2) "65"
    [3]=>
    string(2) "12"
  }
  ["validate"]=>
  array(2) {
    [0]=>
    string(3) "Yes"
    [1]=>
    string(3) "Yes"
  }
}
Hint, it wasn't John and Roger.

 

Now... consider this method. Instead of just naming the form elements name[], age[] and validate[], I instead use the following code:

for($i = 0; $i < 4; $i++) {
?>
	<p>Person #<?=$i?></p>
	<p>Enter Name: <input type="text" name="name[<?=$i?>]" value="" /></p>
	<p>Enter Age: <input type="text" name="age[<?=$i?>]" value="" /></p>
	<p>Validate: <input type="checkbox" name="validate[<?=$i?>]" value="Yes" /></p>
	<hr>
<?php
}
Now that produces a form like this:

<p>Person #0</p>
<p>Enter Name: <input type="text" name="name[0]" value="" /></p>
<p>Enter Age: <input type="text" name="age[0]" value="" /></p>
<p>Validate: <input type="checkbox" name="validate[0]" value="Yes" /></p>
Where $i keeps getting put in the [] for each element. So I have name[0], name[1], name[2] and name[3], along with the same for age[] and validate[]. Now when I submit the form with the same data and same boxes checked as before, can you tell which two names I checked to validate?

array(3) {
  ["name"]=>
  array(4) {
    [0]=>
    string(4) "John"
    [1]=>
    string(5) "Roger"
    [2]=>
    string(7) "Rebecca"
    [3]=>
    string(5) "Bobby"
  }
  ["age"]=>
  array(4) {
    [0]=>
    string(2) "29"
    [1]=>
    string(2) "33"
    [2]=>
    string(2) "65"
    [3]=>
    string(2) "12"
  }
  ["validate"]=>
  array(2) {
    [0]=>
    string(3) "Yes"
    [2]=>
    string(3) "Yes"
  }
}
Link to comment
Share on other sites

Thanks Sepodati.  I'm not relating a text box to a check box. I am not changing any order of the products. Each category already has product and its order associated. The pair is not changing. I am just creating a new line with the same pairs.

cat_assoc_id | prod_id | cat_id | p_order
-------------------------------------------
16101             195              3       6
16102             195              8       3

-------------------------------------------

 

So the next one would be

-------------------------------------------
16103            195              3       6
16104            195              8       3

-------------------------------------------

 

So Item 195 is in category 3 and at position 6 and so on. When the new entry is made all the relation ships in this table remain.

 

3>>>>>6

8>>>>>3

 

I worked it it some and now I am getting some results posted in the p_order column. Just not accurate. Sometimes I get "0" sometimes it duplicates the same number.

 

 

I tried name=ords[] also.

$combined = array_replace($cats,$orders);
				 
	if(count($combined)>0)
					
	{
					
					
	foreach($combined as $cat)
					
	{
	?>
	<tr>
	<td><?php echo $cat['cat_name'];/</td>
	<td><input type='checkbox' name='prodCategories[]' value='<?php echo $cat['cat_id']; ?>' <?php if($editProduct) echo $prod->isCheckSelected($cat['cat_id'], $vals['prod_id']);?>/>
	<input type="hidden" name="ords" value="<?php echo $cat['p_order'];?>" />
						
					

-----------------------------------------------------------------------
$ords =	$_REQUEST['ords'];
	
	for($i= 0; $i < count($cats); $i++)
	
	{
	
	$catCategory = "INSERT INTO category_assoc (prod_id, cat_id, p_order) VALUES('$lastID', '". $cats[$i] . "','$ords')";
		
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.