Jump to content

is this a Magic Quotes problem with PHP Array?


ThunderVike

Recommended Posts

After getting valuable help from DavidAm and wildteen88 I am left with this last piece to the puzzle:

 

I have created a function which identifies the names of multi-value checkbox fields used on a Post page where a form just filled out has been saved in a serialized array which will contain associative arrays wherever the checkboxes have been selected.

 

Now I need for the checkbox associative arrays returned on this Review before-final-saving-page to be detected or identified and then Changed to a comma-delimited array, or maybe it just gets converted to one string with commas separating what were parts of the array--I am not sure about that.

 

At any rate, here are the functions that WORK to do this---but they depend on knowing the specific checkboxes that will show up ahead of time:

 

$postvals['cp_checkbox_amenities']= implode(',', $_POST['cp_checkbox_amenities']);
   $postvals['cp_checkbox_days']= implode(',', $_POST['cp_checkbox_days']);
   $postvals['cp_checkbox_3']= implode(',', $_POST['cp_checkbox_3']);

 

 

So I created a function which polls the form and finds the specific names of the checkboxes used on this page--the function ends like this:

 

        $results = $wpdb->get_results($sql);

        if($results) {

        foreach ($results as $result):
            // now grab all ad fields and print out the field label and value

echo '<li><span>' . $result->field_name . '</li>';

endforeach; 
}

     else {

      echo __('No checkbox details found.', 'cp');

    }

}

}

 

This returns the following:

 

<li><span>cp_checkbox_help</span></li><li><span>cp_checkbox_charley</span></li><li><span>cp_checkbox_hello</span></li>
</li>

 

So, I then tried to REPLACE the hard-code functions I show above that take the checkbox arrays and implode them for saving when this form is updated as comma limited values.

 

I tried various versions of this using the same loop that produced the <li> list with  $result->field_name      :

 

 

       foreach ($results as $result):
            // now grab all ad fields and print out the field label and value

   $postvals['. $result->field_name .']= implode(',', $_POST[ '. $result->field_name .']);

endforeach; 
}

     else {

      echo __('No checkbox details found.', 'cp');

    }

}

}

 

Every different way I try to get something either errors out or does not perform the Implode, or notifies me that the Implode is creating problems.

 

SOMEHOW, dynamically for each loop I need for a ' single quote mark to appear on each side of $result->field_name  so that I have dynamically written in the php code the equivalent to

 

$postvals['cp_checkbox_amenities']= implode(',', $_POST['cp_checkbox_amenities']);
   $postvals['cp_checkbox_days']= implode(',', $_POST['cp_checkbox_days']);
   $postvals['cp_checkbox_3']= implode(',', $_POST['cp_checkbox_3']);

 

the $result->field_name gives me a cp_checkbox_3  or a cp_checkbox_amenities, etc,, but I cannot break it down so that

 

$postvals['$result->field_name']= implode(',', $_POST['$result->field_name']);

 

WORKS

 

and I have tried with [php? echo ''' .$result->field_name . ''' ?>] and other ways.

 

Incidentally, ", double quotes don't play nice on this server with PHP 5.

 

And I have tried combinations of " '  double quote then single quote and on the other side ' " inside the associative array brackets.. nothing works--either I get errors, implode warnings, or the arrays of these checkboxes do not get changed to comma delimited arrays if the page loads and saves without errors.

 

I'd appreciate receiving what must be an elegantly simple solution!

Link to comment
Share on other sites

Hi Wolpie,

 

I tried to explain and show the problem, so let me add this:

 

 

in this code that WORKS  notice the 'cp_checkbox_name' inside the brackets.

 

That is how it works.  The NAME of the checkbox is the same all the way through and is what passes the values and collects them into an array.  Inside the brackets I have to have the single quote marks or the function does not work. ZILCH.

 

That is why, as I am so painstakingly trying to convey, I NEED TO HAVE THE SAME THING...

 

 

As I said, $_POST['cp_checkbox_amenities']  is NOT the same result as $_POST[cp_checkbox_amenities]

 

 

without the ' and the ' in the final functions inside the brackets surrounding the cp_checkbox_amenities or the cp_checkbox_whatevername- -- the name alone returned by $result->field_name does not make anything happen.

Link to comment
Share on other sites

As I said, $_POST['cp_checkbox_amenities']  is NOT the same result as $_POST[cp_checkbox_amenities]

 

You are correct.  The first uses a literal string as the array index, the second is specifying a defined constant as the array index.  However:

$_POST['cp_checkbox_amenities'] = "Hello";

// AND 
$pickBox = 'cp_checkbox_amenities';
$_POST[$pickBox] = "Hello";

// ARE EXACTLY THE SAME

// ALSO
$pickBox = "cp_checkbox_amenities";
$_POST[$pickBox] = 'Hello';

// IS THE SAME THING, TOO

// OH YEAH, THIS IS THE SAME THING TOO.
$pickBox = "cp_checkbox_amenities";
$newValue = "Hello"
$_POST[$pickBox] = $newValue;

and by "SAME THING", I mean you get the same result.

 

The reason for the single-quotes around the checkbox name is that we are using a literal value.  If you use a variable that contains the name, no quotes are needed in the array reference.

 

The major difference between single-quotes and double-quotes is how PHP treats the stuff inside the quotes.  With double-quotes, PHP will scan for and replace variable names and control characters; with single-quotes, it does not.  I personally always use single-quotes unless I need to use double-quotes for parsing or because there are single-quotes in the string.

 

Link to comment
Share on other sites

Thanks, David, for taking a look.

 

How would you APPLY a single quote on both sides of the cp_checkbox_amenities or any other name that comes back from $_POST[$result->field_name] so that when  the next function takes every result---say, three checkbox names return from that:

 

cp_checkbox_1

cp_checkbox_2

cp_checkbox_3

 

Just naked names with no quotes attached.

 

they do not come back with single quotes as in ['cp_checkbox_3']

 

putting the ' inside the bracket...associative array holder...[result->field_name] does not work...using double quotes does not work

 

I had seen notes about using curly brackets inside {} to process a string with a $ but that doesn't seem to work, either.

 

How to set the literal value of EACH

$result->field_name

so that it is equivalent to single-Quoted 'cp_checkbox_1' ?

 

I had thought of first doing some sort of explode that took each returned result and put a ' single quote on each side, but...that seems it will take me more research.

 

There must be a one or two line elegant solution.

 

Then the next loop will work as intended---

 

$postvals[$result->field_name] = implode(',', $_POST[$result->field_name]); 

 

because it sees

 

$postvals['checkbox_1] = implode(',', $_POST['checkbox_1']);

 

This has been mysterious.

Link to comment
Share on other sites

Okay, so it seems that MY situation is outside of all known PHP functions.

 

If a function returns names naked, no quotes, whether single or double--

 

there is just no way anybody has off the top of their heads to output those values WITH a single quote '  ' on both sides??

 

so that cp_checkbox_1 will always output as 'cp_checkbox_1' and any other checkbox value that comes tumbling as a variable out of this function ?

 

The returns of  $result->field_name  is always something without quotes of any kind.

 

I JUST need to output the same thing with a single quote on both sides of the value . Then I can slide it back into this function to get the equivalent of

$postvals[$result->field_name]= implode(',', $_POST[$result->field_name ]);

 

and it is the SAME, exactly stroke for stroke equivalent to this:

 

$_POST['cp_checkbox_1' ]  or $_POST['cp_checkbox_2' ] ad infinitum.

 

Thank you.

 

  I have been all over the internet, day after day, night after night, morning after morning, reading, trying, failing.....HUNDREDS OF TIMES, HUNDREDS AND HUNDREDS of FAILURES with every method I can research.

 

 

Link to comment
Share on other sites

Here's latest thing I tried...using  trim and join to try to place ' ' single quotes around each returned value

BUT, the blankety-blank ' single quote cannot be put there instead of a comma....error, error....

 

       if($results) {

foreach ($results as $result):

     // spit out the array and separate each value with a comma

    $allcats = trim(join(',', $result->field_name));

// this refuses to work as $allcats = trim(join(''', $result->field_name));
// supposedly this uncommented function above puts a COMMA on BOTH SIDES of the //output value from $result->field_name  but that does me no good...I still need the 
// &%&!  single quote ' mark on both sides, not a comma!


   $postvals[$allcats]= implode(',', $_POST[$allcats]);

endforeach; 
}

     else {

      echo __('No checkbox details found.', 'cp');

    }

}

}

 

Link to comment
Share on other sites

Will any of these things help me to change the output so when $result->field_name is looped that it keeps outputting 'cp_checkbox_blah', 'cp_checkbox_doubleblah' even when the value is placed inside an associative array that matches this example

 

$postvals['cp_checkbox_blah']= implode(',', $_POST['cp_checkbox_blah']);

  ??

If you are just joining me the ' single quotes ' have to be inside the array brackets.

 

 

preg_ filter

preg_ grep

preg_ last_ error

preg_ match_ all

preg_ match

preg_ quote

preg_ replace_ callback

preg_ replace

preg_ split

Link to comment
Share on other sites

What I was trying to say is that you do not need the quotes.

 

IF $result->field_name returns cp_checkbox_1 WITHOUT QUOTES, then

$postvals[$result->field_name] = implode(',', $_POST[$result->field_name]);

is exactly the same statement as

$postvals['cp_checkbox_1'] = implode(',', $_POST['cp_checkbox_1']);

 

 

// IF the field_name property of the $result object contains "cp_checkbox_1" ...
$result->field_name = 'cp_checkbox_1';

echo $result->field_name; // WILL print: cp_checkbox_1

// AND 
echo implode(',', $_POST[$result->field_name]);
// WILL print the EXACT SAME THING AS
echo implode(',', $_POST['cp_checkbox_1']);

 

We put quotes around string literals (cp_checkbox_1) because they are NOT variables ($fieldname) and not function names (implode()) and not operators (+), etc. That way the compile or interpreter will have a chance at knowing what it is.  YOU DO NOT NEED THE QUOTES AROUND THE VARIABLE!

 

You could put the quotes inside the variable as part of its value, but then it will not be the same thing:

$result->field_name = 'cp_checkbox_1';
// IS NOT THE SAME AS 
$result->field_name = "'cp_checkbox_1'";

 

So the correct coding from your first post should be:

foreach ($results as $result) {
    // now grab all ad fields and print out the field label and value
    $postvals[$result->field_name]= implode(',', $_POST[$result->field_name]);
}

assuming, of course, that $results is an array of objects that have a property called field_name.

 

If you absolutely want/need the quotes around the value of the variable, then the correct code would be:

foreach ($results as $result) {
    // now grab all ad fields and print out the field label and value
    $postvals["'" . $result->field_name . "'"]= implode(',', $_POST[$result->field_name]);
}

but that will NOT result in the same arrangement we had with the hard-coded values.  In the solution of your other topic, the quotes ARE NOT PART OF THE ARRAY KEY they are simply there to indicate we are using a literal (hard-coded) value for the key.

 

Go back to your other code, and dump the array using print_r():

$postvals['cp_checkbox_amenities']= implode(',', $_POST['cp_checkbox_amenities']);
   $postvals['cp_checkbox_days']= implode(',', $_POST['cp_checkbox_days']);
   $postvals['cp_checkbox_3']= implode(',', $_POST['cp_checkbox_3']);
   print_r($postvals);

you will see that the quotes ARE NOT in the array keys.

Link to comment
Share on other sites

Hello David, thanks so much for taking pity on me  :o

 

There must be something different between your version of PHP and what my server at 1and1.com is  running on.

 

Your code below is EXACTLY what I had written for myself over and over but enclosing the ' single quote in the double quotes did not work.  Never. But I tried, which is why I have kept coming back to the forum.

 

foreach ($results as $result) {
    // now grab all ad fields and print out the field label and value
    $postvals["'" . $result->field_name . "'"]= implode(',', $_POST[$result->field_name]);
}

 

 

You are right, now, when I remove the ' ' from the hard code inside the array brackets the implode with commas works and saves the array that way.  Sometimes it seems as if this server is teasing with me. 

 

So here is the whole function that I have put into the same place in the code JUST before Postvals are updated where the hardcode was

 

$catid = ($_POST['cat']);
// queries the db for the custom ad form based on the cat id and shows any checkboxes
function cp_show_form_checkboxes($catid) {
    global $wpdb;
    $fid = '';

    // call tinymce init code if html is enabled
    if (get_option('cp_allow_html') == 'yes')
        cp_tinymce($width=540, $height=200);

    //$catid = '129'; // used for testing

    // get the category ids from all the form_cats fields.
    // they are stored in a serialized array which is why
    // we are doing a separate select. If the form is not
    // active, then don't return any cats.

    $sql = "SELECT ID, form_cats "
         . "FROM ". $wpdb->prefix . "cp_ad_forms "
         . "WHERE form_status = 'active'";

    $results = $wpdb->get_results($sql);

    if($results) {

        // now loop through the recordset
        foreach ($results as $result) {

            // put the form_cats into an array
            $catarray = unserialize($result->form_cats);

            // now search the array for the $catid which was passed in via the cat drop-down
            if (in_array($catid,$catarray)) {
                // when there's a catid match, grab the form id
                $fid = $result->ID;

                // put the form id into the post array for step2
                $_POST['fid'] = $fid;
            }

        }

    
        // now we should have the formid so show the form layout based on the category selected
        $sql = $wpdb->prepare("SELECT f.field_label, f.field_name, f.field_type, f.field_values, f.field_perm, m.meta_id, m.field_pos, m.field_req, m.form_id "
             . "FROM ". $wpdb->prefix . "cp_ad_fields f "
             . "INNER JOIN ". $wpdb->prefix . "cp_ad_meta m "
             . "ON f.field_id = m.field_id "
             . "WHERE f.field_type = 'checkbox' " 
		 . "AND m.form_id = '$fid' "


             . "ORDER BY m.field_pos asc");


        $results = $wpdb->get_results($sql);

        if($results) {

        foreach ($results as $result):
            // now grab all the field names and loop through them

$postvals[$result->field_name]= implode(',', $_POST[$result->field_name]);

endforeach; 
}

     else {

      echo __('No checkbox details found.', 'cp');

    }

}

}

 

 

And NOW when I try to test it, when I submit an ad it tells me that my session has expired or  that I am trying to submit a duplicate ad....even though I have logged out and started a new admin session.

 

At any rate, there's the whole function that is supposed to loop through the cp_checkbox_this and cp_checkbox_that and implode the array with commas just as the code did.

 

It has been reliably giving me back a cp_checkbox_charley & cp_checkbox_help  & etc for each loop of  $result->field_name.

 

DO I NEED TO SPECIFY A FINAL RETURN OR SOMETHING AT THE END TO MAKE THIS RESPOND?

 

Link to comment
Share on other sites

I am completely through with this...it is heading towards 5 am and it has not worked one single time---

 

THE ARRAY STAYS AN ARRAY AND NEVER EVER GETS CONVERTED.  I SEE THE VALUES REFLECTED ON THE REVIEW PAGE FOR EACH CHECKBOX SELECTED, THE REVIEW PAGE RETURNS A LIST OF THE VALUES SELECTED FOR MY THREE CHECKBOXES.

 

WHEN I SUBMIT AND UPDATE EVERY OTHER VALUE SAVES.  THE CHECKBOX ARRAYS DO NOT GET CONVERTED AND THE AD DOES NOT SHOW THEIR VALUES.

 

HERE IS THE ENTIRE FUNCTION THAT IS MEANT TO REPLACE THE HARD CODE (WHICH WORKS PERFECTLY)

$catid = ($_POST['cat']);
// queries the db for the custom ad form based on the cat id and shows any checkboxes
function cp_show_form_checkboxes($catid) {
    global $wpdb;
    $fid = '';

    //$catid = '129'; // used for testing

    // get the category ids from all the form_cats fields.
    // they are stored in a serialized array which is why
    // we are doing a separate select. If the form is not
    // active, then don't return any cats.

    $sql = "SELECT ID, form_cats "
         . "FROM ". $wpdb->prefix . "cp_ad_forms "
         . "WHERE form_status = 'active'";

    $results = $wpdb->get_results($sql);

    if($results) {

        // now loop through the recordset
        foreach ($results as $result) {

            // put the form_cats into an array
            $catarray = unserialize($result->form_cats);

            // now search the array for the $catid which was passed in via the cat drop-down
            if (in_array($catid,$catarray)) {
                // when there's a catid match, grab the form id
                $fid = $result->ID;

                // put the form id into the post array for step2
                $_POST['fid'] = $fid;
            }

        }

        // now we should have the formid so show the form layout based on the category selected
        $sql = $wpdb->prepare("SELECT f.field_label, f.field_name, f.field_type, f.field_values, f.field_perm, m.meta_id, m.field_pos, m.field_req, m.form_id "
             . "FROM ". $wpdb->prefix . "cp_ad_fields f "
             . "INNER JOIN ". $wpdb->prefix . "cp_ad_meta m "
             . "ON f.field_id = m.field_id "
             . "WHERE f.field_type = 'checkbox' " 
 . "AND m.form_id = '$fid' "
             . "ORDER BY m.field_pos asc");

          $results = $wpdb->get_results($sql);
        if($results) {

        foreach ($results as $result):
            // now grab all ad fields and print out the field label and value

$postvals[$result->field_name]= implode(',', $_POST[$result->field_name]);

endforeach; 
}
     else {

      echo __('No checkbox details found.', 'cp');

    }

}

}

// RIGHT HERE I EVEN REFERRED IMMEDIATELY TO FUNCTION TO SEE IF THIS WOULD MAKE A DIFFERENCE
// WITH OR WITHOUT THIS LINE BELOW IT MAKES NO DIFFERENCE
// THERE ARE NO ERRORS, JUST NO IMPLODED ARRAYS

cp_show_form_checkboxes($catid);

    $option_name = 'cp_'.$postvals['oid'];
    update_option($option_name, $postvals);	
    ?>

 

 

I  am wondering if here--

 

        foreach ($results as $result):
            // now grab all ad fields and print out the field label and value

$postvals[$result->field_name]= implode(',', $_POST[$result->field_name]);

endforeach; 

 

 

if for some reason the $result->field_name doesn't stay the same value all the way through the line

 

as if it becomes $postvals[cp_checkbox_1]= implode(',', $_POST[cp_chckbox_2]);

 

 

but it seems like it would show an error if that were the case.

 

 

Link to comment
Share on other sites

I understand the frustration. There's nothing like having a computer do exactly what you tell it to do, instead of what you want it to do; and then trying to figure out why.

 

It does not look like you did anything with the $postvals array after you built it.  First, check to see if the values are put into the array as expected.  Immediately after the endforeach add this line:

endforeach; 
print_r($postvals);
}

it should dump the array to the screen so you can see the keys and values.  Post them here if they don't look right.

 

What are you expecting to happen with the $postvals after to fill it up? Are you trying to use it in the update_option() function?  You may need to add a return $postvals; to the function to get the array out of it, then process it. So maybe something like this:

$catid = ($_POST['cat']);
// queries the db for the custom ad form based on the cat id and shows any checkboxes
function cp_show_form_checkboxes($catid) {
    global $wpdb;
    $fid = '';

    //$catid = '129'; // used for testing

    // get the category ids from all the form_cats fields.
    // they are stored in a serialized array which is why
    // we are doing a separate select. If the form is not
    // active, then don't return any cats.

    $sql = "SELECT ID, form_cats "
         . "FROM ". $wpdb->prefix . "cp_ad_forms "
         . "WHERE form_status = 'active'";

    $results = $wpdb->get_results($sql);

    if($results) {

        // now loop through the recordset
        foreach ($results as $result) {

            // put the form_cats into an array
            $catarray = unserialize($result->form_cats);

            // now search the array for the $catid which was passed in via the cat drop-down
            if (in_array($catid,$catarray)) {
                // when there's a catid match, grab the form id
                $fid = $result->ID;

                // put the form id into the post array for step2
                $_POST['fid'] = $fid;
            }

        }

        // now we should have the formid so show the form layout based on the category selected
        $sql = $wpdb->prepare("SELECT f.field_label, f.field_name, f.field_type, f.field_values, f.field_perm, m.meta_id, m.field_pos, m.field_req, m.form_id "
             . "FROM ". $wpdb->prefix . "cp_ad_fields f "
             . "INNER JOIN ". $wpdb->prefix . "cp_ad_meta m "
             . "ON f.field_id = m.field_id "
             . "WHERE f.field_type = 'checkbox' " 
             . "AND m.form_id = '$fid' "
             . "ORDER BY m.field_pos asc");

        $results = $wpdb->get_results($sql);
        if($results) {

		foreach ($results as $result):
            // now grab all ad fields and print out the field label and value
			$postvals[$result->field_name]= implode(',', $_POST[$result->field_name]);
		endforeach; 
		return $postvals;  // Return the values so we can process them
	} else {
		echo __('No checkbox details found.', 'cp');
		return array(); // Nothing found so return empty array
	}
} else {
	return array(); // Nothing found so return empty array
}
}

// RIGHT HERE I EVEN REFERRED IMMEDIATELY TO FUNCTION TO SEE IF THIS WOULD MAKE A DIFFERENCE
// WITH OR WITHOUT THIS LINE BELOW IT MAKES NO DIFFERENCE
// THERE ARE NO ERRORS, JUST NO IMPLODED ARRAYS

$postVals = cp_show_form_checkboxes($catid);
foreach ($postVals as $key => $value) {
update_option($key, $value);
}

I added a couple of return statements and another else (for the last return statement) to the function. Then changed the processing of the returned array.

Link to comment
Share on other sites

Hello David, thanks so much for sticking with me this far!

 

I STILL DO NOT GET what I must have, the saving of the checkbox arrays in the final Post / Ad.

 

Here is the read out from the page that Displays what fields have been filled in and what individual checkbox forms have been checked.  The print_r just after the $postvals have been looped and the implosion takes place shows that this IS HAPPENING...these are TEST NAMES until I can finally get this working....

 

Array ( [cp_checkbox_help] => Wednesday, Thursday, Saturday [cp_checkbox_charley] => Cook, Watchman [cp_checkbox_hello] => Pet Friendly: Small dogs allowed with an additional pet deposit,Smoking Allowed: Outdoor areas only,No smoking at all ) 

 

But I notice that the each checkbox, while being imploded is encapsulated in another unnamed Array ()....is this the problem?

 

Don't I have to get rid of the Array () that HOLDS the imploded checkboxes?

 

This function sticks this all back into a holder Array and it is the Array that keeps getting saved, hiding the Checkbox comma delimited []

 

I notice that you although the function I gave you refers to $postvals  in the last foreach loop to update that you deliberately use $postVals.

 

These two lines are the last update lines that seem to take all the postvals put into the $postvals array thus far and update the database when the form is posted.

 

$option_name = 'cp_'.$postvals['oid'];    
    update_option($option_name, $postvals);

 

 

I know that what I must do is make sure that in the sequence of things that the last update action does not go back and Re-UPDATE my custom fields checkbox fields with Array or null just after they have been saved correctly with commas separating values.

 

So, I have experimented over and over with different way to write this and NONE work, including your function...the Ad gets saved incorrectly.  Showing the Title and Price and all those fields fine, but blank Checkboxes...the checkbox fields--  $meta_values, just show Array.

 

So here is what I have, the complete page,including your print_r command.

 

 

<?php
/**
* This is step 2 of 3 for the ad submission form

*
* here we are processing the images and gathering all the post values.
* using sessions would be the optimal way but WP doesn't play nice so instead
* we take all the form post values and put them into an associative array
* and then store it in the wp_options table as a serialized array. essentially
* we are using the wp_options table as our session holder and can access
* the keys and values later and process the ad in step 3
*
*/

global $userdata;
global $wpdb;

// check to see if there are images included
// then valid the image extensions
if (!empty($_FILES['image']))
    $error_msg = cp_validate_image();

// images are valid
if(!$error_msg) {

    // create the array that will hold all the post values
    $postvals = array();

    // upload the images and put into the new ad array
    if (!empty($_FILES['image']))
        $postvals = cp_process_new_image();

    // keep only numeric, commas or decimal values
    if (!empty($_POST['cp_price']))
        $postvals['cp_price'] = cp_clean_price($_POST['cp_price']);
    
    // keep only values and insert/strip commas if needed
    if (!empty($_POST['tags_input']))
        $postvals['tags_input'] = cp_clean_tags($_POST['tags_input']);

    // put all the posted form values into session vars
    foreach($_POST as $key => $value)
        $postvals[$key] = cp_clean($value);

// store the user IP address, ID for later
    $postvals['cp_sys_userIP'] = cp_getIP();
    $postvals['user_id'] = $current_user->ID;

    // see if the featured ad checkbox has been checked
    if ($_POST['featured_ad']) {
        $postvals['featured_ad'] = $_POST['featured_ad'];
        // get the featured ad price into the array
        $postvals['cp_sys_feat_price'] = get_option('cp_sys_feat_price');
    }

    // calculate the ad listing fee and put into a variable
    if(get_option('cp_charge_ads') == 'yes')
        $postvals['cp_sys_ad_listing_fee'] = cp_ad_listing_fee($_POST['cat'], $_POST['ad_pack_id'], $_POST['cp_price']);

    // check to prevent "Notice: Undefined index:" on php strict error checking. get ad pack id and lookup length
    $adpackid = '';
    if(isset($_POST['ad_pack_id'])) {
        $adpackid = $_POST['ad_pack_id'];
        $postvals['pack_duration'] = cp_get_ad_pack_length($adpackid);
    }

    // calculate the total cost of the ad
    $postvals['cp_sys_total_ad_cost'] = cp_calc_ad_cost($_POST['cat'], $adpackid, $postvals['cp_sys_feat_price'], $_POST['cp_price']);
    // Debugging section
    //echo '$_POST ATTACHMENT<br/>';
    //print_r($postvals['attachment']);

    //echo '$_POST PRINT<br/>';
    //print_r($_POST);

    //echo '<br/><br/>$postvals PRINT<br/>';
    //print_r($postvals);

    // now put the array containing all the post values into the database
    // instead of passing hidden values which are easy to hack and so we
    // can also retrieve it on the next step

$catid = ($_POST['cat']);


$catid = ($_POST['cat']);
// queries the db for the custom ad form based on the cat id and names any checkboxes to be included
function cp_show_form_checkboxes($catid) {
    global $wpdb;
    $fid = '';

    //$catid = '129'; // used for testing

    // get the category ids from all the form_cats fields.
    // they are stored in a serialized array which is why
    // we are doing a separate select. If the form is not
    // active, then don't return any cats.

    $sql = "SELECT ID, form_cats "
         . "FROM ". $wpdb->prefix . "cp_ad_forms "
         . "WHERE form_status = 'active'";

    $results = $wpdb->get_results($sql);

    if($results) {

        // now loop through the recordset
        foreach ($results as $result) {

            // put the form_cats into an array
            $catarray = unserialize($result->form_cats);

            // now search the array for the $catid which was passed in via the cat drop-down
            if (in_array($catid,$catarray)) {
                // when there's a catid match, grab the form id
                $fid = $result->ID;

                // put the form id into the post array for step2
                $_POST['fid'] = $fid;
            }

        }

        // now we should have the formid so show the form layout based on the category selected
        $sql = $wpdb->prepare("SELECT f.field_label, f.field_name, f.field_type, f.field_values, f.field_perm, m.meta_id, m.field_pos, m.field_req, m.form_id "
             . "FROM ". $wpdb->prefix . "cp_ad_fields f "
             . "INNER JOIN ". $wpdb->prefix . "cp_ad_meta m "
             . "ON f.field_id = m.field_id "
             . "WHERE f.field_type = 'checkbox' " 
             . "AND m.form_id = '$fid' "
             . "ORDER BY m.field_pos asc");

        $results = $wpdb->get_results($sql);
        if($results) {
		foreach ($results as $result):
            // now grab all ad fields and print out the field label and value
			$postvals[$result->field_name]= implode(',', $_POST[$result->field_name]);
		endforeach;
		print_r($postvals);
		return $postvals;  // Return the values so we can process them
	} else {
		echo __('No checkbox details found.', 'cp');
		return array(); // Nothing found so return empty array
	}
} else {
	return array(); // Nothing found so return empty array
}
}


$catid = ($_POST['cat']);
$postVals = cp_show_form_checkboxes($catid);
foreach ($postVals as $key => $value) {
update_option($key, $value);
}

//these are the lines below that wrap things all up for the submit form
// the oid is the session and the cp_is to distinguish all these values from regular Wordpress

$option_name = 'cp_'.$postvals['oid'];    
    update_option($option_name, $postvals);
    ?>

    <div id="step2"></div>

      <h2 class="dotted"><?php _e('Review Your Listing','cp');?></h2>

            <img src="<?php bloginfo('template_url'); ?>/images/step2.gif" alt="" class="stepimg" />
<?php // this is where the completed form first comes back to look at while in the add new ad process ?>

            <form name="mainform" id="mainform" class="form_step" action="" method="post" enctype="multipart/form-data">



                <ul>

                    <?php  
                    // pass in the form post array and show the ad summary based on the formid

                    echo cp_show_review($postvals);

                    // debugging info

                    // debugging info
                    //echo get_option('cp_price_scheme') .'<-- pricing scheme<br/>';
                    //echo $postvals['cat'] .'<-- catid<br/>';
                    //echo get_option('cp_cat_price_'.$postvals['cat']) .'<-- cat price<br/>';
                    //echo $postvals['user_id'] .'<-- userid<br/>';
                    //echo get_option('cp_price_per_ad') .'<-- listing cost<br/>';
                    //echo get_option('cp_curr_symbol_pos') .'<-- currency position<br/>'; 
?>
				                <li>
                <?php 
if($postvals['cp_sys_total_ad_cost'] > 0) : ?>
                <label><?php _e('Payment Method','cp'); ?>:</label>
                <select name="cp_payment_method" class="dropdownlist required">
                    <?php if(get_option('cp_enable_paypal') == 'yes') { ?><option value="paypal"><?php echo _e('PayPal', 'cp') ?></option><?php } ?>
                    <?php if(get_option('cp_enable_gcheckout') == 'yes') { ?><option value="gcheckout"><?php echo _e('Google Checkout', 'cp') ?></option><?php } ?>
                    <?php if(get_option('cp_enable_2checkout') == 'yes') { ?><option value="2checkout"><?php echo _e('2Checkout', 'cp') ?></option><?php } ?>
                    <?php if(get_option('cp_enable_authorize') == 'yes') { ?><option value="authorize"><?php echo _e('Authorize.net', 'cp') ?></option><?php } ?>
                    <?php if(get_option('cp_enable_chronopay') == 'yes') { ?><option value="chronopay"><?php echo _e('Chronopay', 'cp') ?></option><?php } ?>
                    <?php if(get_option('cp_enable_mbookers') == 'yes') { ?><option value="mbookers"><?php echo _e('MoneyBookers', 'cp') ?></option><?php } ?>
                </select>
                <?php endif; ?>
                <div class="clr"></div>
                </li> 


                </ul>

                <div class="pad10"></div>


	<div class="license">

                    <?php echo get_option('cp_ads_tou_msg'); ?>

	</div>

                <div class="clr"></div>


                <p class="light"><?php _e('By clicking the proceed button below, you agree to our terms and conditions.','cp'); ?>
                <br/>
                <?php _e('Your IP address has been logged for security purposes:','cp'); ?> <?php echo $postvals['cp_sys_userIP']; ?></p>


                <p class="btn2">
                    <input type="button" name="goback" class="btn_orange" value="<?php _e('Go back','cp') ?>" onclick="history.back()" />
                    <input type="submit" name="step2" id="step2" class="btn_orange" value="<?php _e('Proceed ','cp'); ?> ››" />
                </p>

                    <input type="hidden" id="oid" name="oid" value="<?php echo $postvals['oid']; ?>" />
                 

    </form>


	<div class="clear"></div>

<?php

} else {

?>

    <h2 class="dotted"><?php _e('An Error Has Occurred','cp') ?></h2>
    
    <div class="thankyou">
        <p><?php echo cp_error_msg($error_msg); ?></p>
        <input type="button" name="goback" class="btn_orange" value="‹‹ <?php _e('Go Back','cp') ?>" onclick="history.back()" />
    </div>
  

<?php
}
?>

 

 

Thanks so much, David, for helping me see the light at the end of a very long dark tunnel!

 

David in Vienna

Link to comment
Share on other sites

Hello David,

 

Here is what I think is critically DIFFERENT about your method from the Hardcode example below which WORKS

 

 

   $postvals['cp_checkbox_charley']= implode(',', $_POST['cp_checkbox_charley']);
   $postvals['cp_checkbox_help']= implode(',', $_POST['cp_checkbox_help']);
   $postvals['cp_checkbox_hello']= implode(',', $_POST['cp_checkbox_hello']);


//these are the two lines that do the final wrap up and save to the database 
//and note that these are meant to be values distinguished from the regular Wordpress save of values.  

    $option_name = 'cp_'.$postvals['oid'];
    update_option($option_name, $postvals);

 

In your function I notice you do the update while distinguishing the checkbox values as $postVals with a capital 'V'

 

However, in the hardcode above the

 

$postvals['cp_checkbox_charley']  STAYS like that -- IMPLODED with commas.  It sits there as a static value now.

 

it does not get wrapped with another ARRAY.

 

In your function, apparently once all the checkboxes have been imploded then they get saved all together as one more unnamed "bundled" Array. 

 

This Array now HIDES my imploded checkboxes rather than exposing them to being saved as separate checkboxes....

 

Once each checkbox is imploded then it should stay separate, just as the hardcode example does.  Nothing happens to each checkbox until it is assembled for the $postvals array for updating....so the checkboxes arrive ready to be put into their appropriate fields.

 

The function you have given me stuffs all the imploded checkboxes back into an anonymous array and THEN into $postvals.

 

Unless I am seeing this wrong.

 

 

 

Link to comment
Share on other sites

OOOPS, I see that my assumption was wrong.... the () WAS CAUSED BY THE PRINT FUNCTION!

 

MY MISTAKE.

 

But evidently my assumption is correct that what I need is the equivalent of the hardcode....

 

separate postvals for each checkbox that hold the result of the IMPLODE

 

and to not get all of the separate checkboxes then PREMATURELY Enclosed in one big array holding all the newly imploded checkbox values.

Link to comment
Share on other sites

Ok, David, seeing a little more of the code might have helped me understand what is (and should be) happening.

 

So "* This is step 2 of 3 for the ad submission form" starts processing the POSTed fields, and loading them into an array named $postvals so you can submit them to the update process later.

 

By the way, is there a typo in this section?

    if (!empty($_FILES['image']))
        $postvals = cp_process_new_image();

should that be $postvals['image']? Because otherwise it is overwriting whatever is already there and the next assignment is overwriting that?  Of course, I don't know what cp_process_new_image() is doing so I could be wrong.

 

So, when you get through processing the non-checkbox fields, you call cp_show_form_checkboxes() to handle the checkboxes (which are POSTed as an array and need to be imploded).  Now, inside this function you load the checkbox values into $postvals.  BUT REMEMBER, you are inside a function, so this is NOT THE $postvals that you were loading OUTSIDE the function.  Functions do not have access to the variables that are defined OUTSIDE the function. 

 

If I read this correctly, you want to be adding the imploded checkboxes to the SAME $postvals you used before.  There are a couple of ways to accomplish this.  The "recommended" way is to pass a reference to that variable into the function.  So your function definition would be:

 

function cp_show_form_checkboxes($catid, &$postvals) { // We use & to get the reference

 

Then you can take out the 3 returns I added at the end of the function.

And take out the foreach loop I added after the function

Finally, change your call to the function to this:

 

} // THIS IS THE CLOSING BRACKET ON THE FUNCTION DEFINITION


$catid = ($_POST['cat']);
cp_show_form_checkboxes($catid, $postvals);
// NOTE: IF YOU ARE NOT USING PHP 5 you will need to change that to
// cp_show_form_checkboxes($catid, &$postvals);

/* REMOVE THIS STUFF - I GUESS I SHOULDN'T HAVE BEEN GUESSING
foreach ($postVals as $key => $value) {
update_option($key, $value);
}
** END OF REMOVE THIS STUFF */

// A print_r() here should show EVERYTHING in $postvals
// print_r($postvals);

//these are the lines below that wrap things all up for the submit form
// the oid is the session and the cp_is to distinguish all these values from regular Wordpress

$option_name = 'cp_'.$postvals['oid'];    
    update_option($option_name, $postvals);

 

Of course there are other ways to do this.  You could just add $postvals to your global statement INSIDE the function.  Typically, you want to avoid the use of globals inside functions, though.

 

Does all that make sense with what you are expecting to accomplish?  I'll look through this again when I get home (in about 2 hours) and let you know if I see something different.

Link to comment
Share on other sites

Hello David, thanks so much for taking another look!

 

There are several files that contain functions that are referred to but the image loader always works perfectly. And the full Image handler script is not included here!  It is in a separate file.

 

I am going to try right now to see what happens with your suggestions!

Link to comment
Share on other sites

WOWWWW!!!! 

 

THAT WAS IT!

 

It works, it works!!!

 

Your addition of

 

function cp_show_form_checkboxes($catid, &$postvals) {

  was CRUCIAL! 

 

What an AMAZING difference THAT made

 

so the &$postvals  PASSES the other $postvals THROUGH?

 

I thought that the postvals were being assembled in little modules along the way waiting for the checkbox additions.

 

What exactly did your change do in the flow?

 

Thanks a MILLION!

 

DAVID---YOU the man!  And thank you again wildteen88!

 

 

 

 

 

Link to comment
Share on other sites

You said "Functions do not have access to the variables that are defined OUTSIDE the function."

 

THAT is an important point.

 

I thought that since I could SEE the other $postvals being stored in the lines above this function that by following sequentially those stored $postvals already stored in the session with my function and naming $postvals AGAIN in my function that I was lining them up for INCLUSION on the update.

 

PASSING the values THROUGH this function was a big concept to learn!

 

THANK YOU AGAIN!

Link to comment
Share on other sites

Glad I could help. Sorry we took the long way around.  I couldn't really tell where we were trying to go at first.

 

The change we made to the function passed a reference to the variable instead of a copy.  That allowed us to modify the variable INSIDE the function and have those changes remain OUTSIDE the function.  Read up on variable SCOPE.

 

Basically, anything defined inside the function is local to the function and has nothing to do with the stuff outside the function.  This is a key concept in programming.  Take this example:

<?php
/* Here is a function definition - 
      It does not matter where this is in the code, 
        it is DEFINED here but NOT executed. */
function fred($input) {
  echo 'INSIDE1: ' . $input . '<BR>';
  $input = 'green';
  echo 'INSIDE2: ' . $input . '<BR>';
}

// MAIN PROGRAM LOGIC STARTS HERE
$someVar = 'sky';
echo 'OUTSIDE1: ' . $someVar . '<BR>';

// Here we call the function to execute the code inside it
fred($someVar);

echo 'OUTSIDE2: ' . $someVar . '<BR>';

the output from this is:

OUTSIDE1: sky
INSIDE1: sky
INSIDE2: green
OUTSIDE2: sky

 

Notice the following:

[*]When we call the function, we include a variable (in the parenthesis) whose value is passed to the function, this is called a parameter;

[*]In the function definition, we used a different name for the parameter. That's fine because inside the function has nothing to do with outside the function; we can use the same name if we want, it just does not matter;

[*]We changed the parameter's value INSIDE the function; the two echos inside show we received the original value AND we changed that value;

[*]The last echo, after the function call - OUTSIDE the function - shows that the change we made INSIDE the function had no affect on the variable OUTSIDE the function. That's because PHP actually passed a copy of the variable's value.

 

However we can add just one single character to this code and make a dramatic change:

<?php
/* Here is a function definition - 
      It does not matter where this is in the code, 
        it is DEFINED here but NOT executed. */
function fred(&$input) { // <== ONE SINGLE CHARACTER ADDED HERE
  echo 'INSIDE1: ' . $input . '<BR>';
  $input = 'green';
  echo 'INSIDE2: ' . $input . '<BR>';
}

// MAIN PROGRAM LOGIC STARTS HERE
$someVar = 'sky';
echo 'OUTSIDE1: ' . $someVar . '<BR>';

// Here we call the function to execute the code inside it
fred($someVar);

echo 'OUTSIDE2: ' . $someVar . '<BR>';

the output from this is:

OUTSIDE1: sky
INSIDE1: sky
INSIDE2: green
OUTSIDE2: green

Notice that OUTSIDE2 now shows "green".  That's the value we set INSIDE the function. This works because the ampersand ('&') we added in the function definition tells PHP to pass the parameter BY REFERENCE. Which means everything we do to that parameter INSIDE the function is affecting the ORIGINAL variable that was passed in.  You will note that it still does not matter if we use the same name or not.

 

Version Note: This works in PHP 5. In PHP 4 we had to put the ampersand (&) at the function call and in the definition.  So the function call would have been: fred(&$someVar);  I'm not sure if this is an improvement or not.  I liked the PHP 4 way in some respects, because I could choose to pass a copy or a reference depending on what I needed in a specific call. But, such is life.  If you use this "call by reference" in PHP 5, you get a notice that it is depricated.

Link to comment
Share on other sites

Thanks so MUCH!

 

I am reading your post.

 

You should write some Tutorials!!

 

I have read a lot of them but they usually wind up with examples that JUST MISS "my" situation.

 

I am running PHP 5+

 

It must be a pain trying to write public software with "fall back" options in case the PHP is an earlier version.

 

It was weird watching the IMPLODE happening, seeing it, but not being able to Update it.

 

Thank you for your thoroughness and willingness to wade through all that!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.

×
×
  • 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.