Making Multiple array selection in Form to be sticky when editing other items 2

Dear all, whenever I want to edit other inputs like images in the snippet of codes below the array of input in size select input always wipe off if I don’t reinsert the sizes that I choose initially in it because it is an array element.
Please, how can I make it stiky if I don’t re-choose the same sizes I entered while inserting the product.

    <form>  
       <select name="size[]" multiple="multiple" style="height:150px;" class="form-control"><option value="<?php echo $size; ?>"> <?php echo $size; ?> </option>
                          <?php 
                          $get_sizes = "select * from sizes";

                          $run_sizes = mysqli_query($con,$get_sizes);
                          while ($row_sizes=mysqli_fetch_array($run_sizes)){
                              $size_id = $row_sizes['size_id'];

                              $size = $row_sizes['size'];
                              echo "
                              <option value='$size'> $size </option>
                              ";
                          }
                          ?>
                      </select><!-- form-control Finish -->
    <?php  

if(isset($_POST['update'])){
    $product_title =  mysqli_real_escape_string($con, trim($_POST['product_title']));

    $product_url =mysqli_real_escape_string($con, trim($_POST['product_url']));

    $product_cat = $_POST['product_cat'];

    $product_cat = implode(", ", $product_cat);

    $cat = mysqli_real_escape_string($con, trim($_POST['cat'])); 

    $size = $_POST['size'];

    $size = implode(", ", $size);

    $manufacturer_id = mysqli_real_escape_string($con, trim($_POST['manufacturer']));

    $product_price = (INT) $_POST['product_price'];

    $product_keywords = mysqli_real_escape_string($con, trim($_POST['product_keywords']));

    $product_desc = mysqli_real_escape_string($con, trim($_POST['product_desc']));

    $product_features = mysqli_real_escape_string($con, trim($_POST['product_features']));

    $product_video = $_POST['product_video'];

    $product_seo = mysqli_real_escape_string($con, trim($_POST['seo_keywords']));

    $product_sale = mysqli_real_escape_string($con, trim($_POST['product_sale']));

    $product_label =  mysqli_real_escape_string($con, trim($_POST['product_label']));

    if(is_uploaded_file($_FILES['product_img1']['tmp_name']) || ($_FILES['product_img2']['tmp_name']) || ($_FILES['product_img3']['tmp_name'])){

            // work for upload / update image
        $product_img1 = $_FILES['product_img1']['name'];

        $product_img2 = $_FILES['product_img2']['name'];

        $product_img3 = $_FILES['product_img3']['name'];
        $temp_name1 = $_FILES['product_img1']['tmp_name'];

        $temp_name2 = $_FILES['product_img2']['tmp_name'];

        $temp_name3 = $_FILES['product_img3']['tmp_name'];
move_uploaded_file($temp_name1,"product_images/$product_img1");
move_uploaded_file($temp_name2,"product_images/$product_img2");
move_uploaded_file($temp_name3,"product_images/$product_img3");
 
  $update_product = "update products set p_cat_id='$product_cat',cat_id='$cat',size='$size',manufacturer_id='$manufacturer_id',date=NOW(),product_title='$product_title',product_url='$product_url',product_img1='$product_img1',product_img2='$product_img2',product_img3='$product_img3',product_keywords='$product_keywords',product_desc='$product_desc',product_price='$product_price',product_sale='$product_sale',product_label='$product_label',product_features='$product_features',product_video='$product_video' where product_id='$p_id'";
        $run_product = mysqli_query($con,$update_product);
        if($run_product){
        echo "<script>alert('Your product has been updated Successfully')</script>"; 
        echo "<script>window.open('index.php?view_products','_self')</script>"; 
        }
    }else{

I deleted your first post as it was not readable!

This post is badly formatted, too. Why all of the blank lines? Hard to read!

Now, I am not sure exactly what your question is, but I will guess. Do you mean that you want entries from previous ones to stay in the fields? If so, you will need to load them from the old versions. Since your code is hard to read, and a lot of it is just one big line, I am not sure. Normally, you load values from a database and you have default values that the fields will be set at. If you want to allow the last value to be placed into a field, you have to save it somehow. Most programmers would just save that in the $_SESSION array from page to page. So, you would save the size options in the $_SESSION and they would be reloaded when the page is refreshed.

Also, mysqli_real_escape_string is no longer used. It has been replaced with filter_input() functions. You should read up on that. Hope this helps. Please format your next post better. Thank you.

Also, what are you trying to do with this line? It makes no sense at all.
Implode() lets you take an array and turn it into a string. In this format, it does nothing since $size is already a string!

@olaoyesunday, I added bbcode [code][/code] tags around and removed the large blocks of white-space from your code.

As to the coding pattern you are using. This php code consists almost entirely of lines of code repeated for each input, but in this wall of code, you don’t have necessary things like validation logic. This is just a waste of typing. You should keep the input data as an array (arrays are for sets of things that will operated on in the same/similar way), then use array functions to dynamically operate on the data. You should actually dynamically build the sql query statement, but this is an advanced subject left for a different time. By using a prepared query, all the …escape_string() statements will go away, the sql query syntax will be simplified, and the query will be safe for all data types. You should also switch to the much simpler PDO database extension.

To edit/update existing data, you would initially retrieve the existing data values, if the form has not been submitted, store them in a common working array variable, then use the contents of the common working variable throughout the rest of code, i.e. to populate the form field values.

To re-populate the form field values, upon a validation error, after the form has been submitted, you would copy the submitted form data into the same common working variable mentioned above, so that the user doesn’t need to keep reentering the same changes over and over.

To accomplish this interlocking logic, lay your code out as follows -

$post = []; // common variable to hold a trimmed working copy of the form data and to hold the initial data being edited
$errors = []; // an array to hold validation/user error messages

// inside the post method form processing code -
// trim all the data at once and store in the common working variable
$post = array_map('_trim', $_POST); // since some of the form fields are arrays, the _trim call-back function used here needs to be a user written recursive trim function. if i/someone has time, they will post an example of how to do this.

// validate all the inputs here, in $post, storing validation errors in the $errors array, using the form field name as the array index

// if no errors, use the submitted data, in $post
if(empty($errors))
{
    // build and execute the UPDATE query here...
}
// end of the form processing code

// get the initial data, if the form has not been summitted, $post will be empty
if(empty($post))
{
    // query for the existing data and store in $post, in the same format as the submitted form data will be in
}

// inside the html document, display any errors in the $errors array and use the contents of $post to (re)populate the form field values

If you need more specific help with the product_cat and size arrays, ask and someone can post examples on how you would pre-select the option choices (you would use in_array() to test if the current option being output is in the array of existing/submitted form data.)

You should not store comma separated lists in a database table column, you would instead have products_product_cat and products_size tables to hold the selected categories and sizes, one row per value, related back to the product they belong to through the product id.

Hi ErnieAlex,
Thanks for your suggestions and help.
If you look at the code very well I shortened it because what I am asking is " I’m updating the code which I called edit_product.php. The code is perfectly working well but where I am having issues is the first HTML that I wrote Select Input. inside it from product.php I have array of sizes like 24D, 25DD, 27AA, et.c and converted them to a single string under sizes on the product page, for example you searched for push-up bra from dunniessentials.com and it gives you the above size as the available sizes.
But my question is this anytime updating the product from edit_product.php. this

<option value="<?php echo $size; ?>"> <?php echo $size; ?> </option>

the above code doesn’t bring the saved sizes from product.php to edit_product.php.

Well, if you have a SELECT which has multiple sizes in it, such as:
< select name=“size”> < option value=“1”>1< /option>< option value=“2”>2< /option>< /select>
Then, you can only pass one of those values. Whichever the user selects before the page is posted.
Therefore your code:

will get whichever size the user selects. If you need to also pass ALL of the sizes to another page, you would need to save it as an array and pass that. Loosely something like this:
$all_sizes = array(“1”, “2”, “more sizes”);
And, then pass it either inside a SESSION variable or using HTML such as this:
< ?PHP
$size_array=implode("," , $all_sizes);
echo “< input type=“hidden” name=“all_sizes” value=’” . $size_array . “’ . >”;
NOTE: the value clause uses single quotes for the HTML part, but, ends and restarts with double-quotes!
You can use slashes, but, easier just to use single and double quotes…

Is that way you are asking?
Ernie

@ErnieAlex, the multiple select/option menu is an array, which will hold all the options that have been selected.

See the following working demo showing the points that were given -

<?php
// recursive function to trim data
function _trim($val){
	if(is_array($val)){
		return array_map('_trim',$val);
	} else {
		return trim($val);
	}
}

$post = []; // common variable to hold a trimmed working copy of the form data and to hold the initial data being edited
$errors = []; // an array to hold validation/user error messages

// post method form processing code
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// trim all the data at once and store in the common working variable
	$post = array_map('_trim', $_POST); // since some of the form fields are arrays, the _trim call-back function used here needs to be a user written recursive trim function
	
	// examine data for demo purposes
	print_r($post);

	// validate all the inputs here, in $post, storing validation errors in the $errors array, using the form field name as the array index

	// if no errors, use the submitted data, in $post
	if(empty($errors))
	{
		// build and execute the UPDATE query here...
	}
}

// get the initial data, if the form has not been submitted, $post will be empty
if(empty($post))
{
    // query for the existing data and store in $post, in the same format as the submitted form data will be in
	
	// fake some values
	$post['size'][] = 1;
	$post['size'][] = 2;
}

// get the size choices
$sql = "SELECT size_id, size FROM sizes"; // should have an ORDER BY ... term to insure that result is in an expected order

// fake some values
$size_choices[] = ['size_id'=>1,'size'=>'s'];
$size_choices[] = ['size_id'=>2,'size'=>'m'];
$size_choices[] = ['size_id'=>3,'size'=>'l'];
$size_choices[] = ['size_id'=>4,'size'=>'xl'];


// inside the html document, display any errors in the $errors array and use the contents of $post to (re)populate the form field values
?>

<form method='post'>
<select name="size[]" multiple="multiple" style="height:150px;" class="form-control">
<option value="">Select one or more size(s)</option>
<?php
foreach($size_choices as $row)
{
	$sel = isset($post['size']) && in_array($row['size_id'],$post['size']) ? ' selected' : '';
	echo "<option value='{$row['size_id']}'$sel>{$row['size']}</option>";
}
?>
</select>
<input type='submit'>
</form>

Thanks @ErnieAlex and @phdr For your help, it really helps me.

Sponsor our Newsletter | Privacy Policy | Terms of Service