SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    Shropshire
    Posts
    203
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Serialize within foreach loop

    Currently banging my head against a brick wall and I am sure it will be something very simple.

    I am trying to submit data from a form into a nested foreach loop to insert into a database (one insert per the outer foreach loop) whilst serializing the inner foreach loop (to insert the serialized data into one column per outer foreach loop), but with the various options of code I have tried, I either get no insert for the serialized column, or the same serialized data into each row of the outer foreach loop, or the highest value from each inner loop inserted into each row.

    My current php code (though I don't know where I am with it now so may be awful), is:
    PHP Code:
    foreach ($_POST['helpdays'] as $key=>$helping) {
            
            
    $jobs=array($_POST['job_id']);
            
    $jobs_serialized=serialize($_POST['job_id']);
            
            
    pg_query("INSERT INTO shows_helpers_jobs_times (helper_id, day_id, job_time_id, jobs, judge, ring_party) values (
                '" 
    pg_escape_string($shows_helper_id) . "',
                '" 
    pg_escape_string($helping['day_id']) . "',
                '" 
    pg_escape_string($helping['job_time_id']) . "',
                '" 
    $jobs_serialized "',
                '" 
    pg_escape_string($helping['judge']) . "',
                '" 
    pg_escape_string($helping['ring_party']) . "')");
                
            } 
    And the form / posted data comes from:

    HTML Code:
    <form name="helping" action="offer-help.php" method="post">
                            <div class="formheadlarge">Helper</div>
                            <div class="formlarge">
                        <p><span class="infolabelcamping">First Name:</span><input type="text" name="helper_name" class="fields" size="30"  /></p>
                        <p><span class="infolabelcamping">Surame:</span><input type="text" name="helper_surname" class="fields" size="30"  /></p>
                        </div>
                            <div class="formheadlarge">Helping Details</div>
                            <div class="formlarge">
                        <?php
                        $total_days=0;
                        while ($dayrow=$helper_days->get_row()) { $day_id=$dayrow['day_id']; ?>
                        <h3><?php echo $dayrow['day'];?> <input type="checkbox" id="day_id[<?php echo $total_days;?>]" name="helpdays[<?php echo $total_days;?>][day_id]" value="<?php echo $day_id;?>"></h3>
                        <?php if ($helper_job_req=='t') { ?>
                        <p><span class="highlight">Job(s)</span> - please select all that you are willing to do:<br /> 
                        <?php
                        $helper_jobs = new helpers;
                        $helper_jobs->show_id=$_SESSION['show_id'];
                        $helper_jobs->load_jobs();
                        $total_jobs=0;
                        while ($jobrow=$helper_jobs->get_row()) { ?>
                        <?php echo $jobrow['job'];?><input id="job_id[<?php echo $total_jobs;?>]" name="jobs[<?php echo $total_jobs;?>][job_id]" type="checkbox" value="<?php echo $jobrow['job_id'];?>" class="fields" />&nbsp;
                        <?php $total_jobs++; } ?>
                        </p>
                        <?php } if ($helper_time_req=='t') { ?>
                        <p><span class="highlight">Time:</span><br />
                        <?php
                        $helper_job_times = new helpers;
                        $helper_job_times->show_id=$_SESSION['show_id'];
                        $helper_job_times->load_job_times();
                        while ($timerow=$helper_job_times->get_row()) { ?>
                        <?php echo $timerow['job_time'];?><input id="job_time_id[<?php echo $total_days;?>]" name="helpdays[<?php echo $total_days;?>][job_time_id]" type="radio" value="<?php echo $timerow['job_time_id'];?>" class="fields" />&nbsp;
                        <?php } ?>
                        <input type="hidden" id="job_time_id[<?php echo $total_days;?>]" name="helpdays[<?php echo $total_days;?>][job_time_id]" value="1" />
                        <?php } else { ?>
                        <input type="hidden" id="job_time_id[<?php echo $total_days;?>]" name="helpdays[<?php echo $total_days;?>][job_time_id]" value="1" />
                        </p>
                        <?php } if ($judge_req=='t') {?>
                        <p><span class="infolabel">With Judge:</span> <input type="text" id="judge[<?php echo $total_days;?>]" name="helpdays[<?php echo $total_days;?>][judge]" class="fields" size="26" />  (if applicable)</p>
                        <?php } if ($ring_party_req=='t') {?>
                        <p><span class="infolabel">Ring Party:</span> <input type="text" id="jring_party[<?php echo $total_days;?>]" name="helpdays[<?php echo $total_days;?>][ring_party]" class="fields" size="26" /> (if pre-arranged)</p>
                        <?php } ?>
                        <hr class="dot" />
                        <?php $total_days++; } ?>
                            </div>
                            <input type="hidden" name="offer" value="1" />
                            <input name="Submit" type="submit" class="formbutt" value="Submit Helping Offer" />
                            <input name="more_help" type="submit" class="formbutt" value="Submit &amp; Offer More Help" />
                        </form>
    I don't know if it is the form, the foreach loop or the serialize part of the code which is worng and I really would appreciate some help on this.

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    >I don't know if it is the form, the foreach loop or the serialize part of the code which is worng and I really would appreciate some help on this.

    I would say you need to develop a strategy to deal with this problem.

    The problem is'nt the code - your problem is you aren't seemingly able to isolate where the problem is.

    1 Is the form well formed, and when filled in does the data make the trip from the client to the server?

    2 Is the data well formed when it arrives?

    3 Does the sql work as expected?

    4 Is there a logic problem on the page storing the details?

    5 Is there another problem?

    If you dont know where the problem IS NOT then its awfully hard for anyone remotely to try and "fix it" for you.

    I'd suggest:

    1 look at the output of your form, html page -> inspect the source code - got empty values? quotes opened but not closed? Use firefox as your browser and look at the Tidy screen.

    2 When you submit your form, do this:
    print_r($_POST);
    and look inside your variables

    3 echo the sql statement onto the page and have a good look at it. Paste the sql statement directly into your database, is it well formed - what happened - what errors does it come out with.
    If you hard code some test values into your sql statement - does that even work?

    4 If all the above works, then theres likely a problem here.
    Turn error reporting on at the top of the page like this:
    PHP Code:
    ini_set('display_errors'1);
    error_reporting(E_ALL); 
    5 If youve done all of the above and still have a problem, then come back and ask us ....

    ps Don't forget to turn all of that off when you publish the page.

    HTH

  3. #3
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    Shropshire
    Posts
    203
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for that, it gave me sothing to work from / with and in answer to your points:

    1. The source code is fine (all values present and correct).

    2. I have printed out the posted variables and get what I think is correct (see below for what I get displayed).

    3. The data inputs into the database fine, it is just getting the inner array of job_id's to be serialized that I am having a problem with so no problem with the sql.

    4. I have turned on display errors and at present I am getting some errors regaring null values and undefined indexes which I need to look into further - is this because blank values are being posted in the array? If so, can this be stopped?

    I have slightly changed the code again in the form and foreach loop:

    PHP Code:
    $helpers_form = (isset ($_POST['helpdays'])) ? $_POST['helpdays'] : array();
        foreach (
    $_POST['helpdays'] as $key=>$helping) {
            
            
    $jobs_serialized=serialize($helping['job_id']);
            
            
    pg_query("INSERT INTO shows_helpers_jobs_times (helper_id, day_id, job_time_id, jobs, judge, ring_party) values (
                '" 
    pg_escape_string($shows_helper_id) . "',
                '" 
    pg_escape_string($helping['day_id']) . "',
                '" 
    pg_escape_string($helping['job_time_id']) . "',
                '" 
    $jobs_serialized "',
                '" 
    pg_escape_string($helping['judge']) . "',
                '" 
    pg_escape_string($helping['ring_party']) . "')");
                
            } 
    And the part of the form where the jobs are selected has now changed from
    HTML Code:
    $total_jobs=0;                                                            
                        while ($jobrow=$helper_jobs->get_row()) { ?>
                        <?php echo $jobrow['job'];?><input id="job_id[<?php echo $total_jobs;?>]" name="helpdays[<?php echo $total_days;?>[<?php echo $total_jobs;?>]][job_id]" type="checkbox" value="<?php echo $jobrow['job_id'];?>" class="fields" />&nbsp;
                        <?php $total_jobs++; } ?>
    to
    HTML Code:
    $total_jobs=0;                                                            
                        while ($jobrow=$helper_jobs->get_row()) { ?>
                        <?php echo $jobrow['job'];?><input id="job_id[<?php echo $total_jobs;?>]" name="helpdays[<?php echo $total_days;?>[<?php echo $total_jobs;?>]][job_id]" type="checkbox" value="<?php echo $jobrow['job_id'];?>" class="fields" />&nbsp;
                        <?php $total_jobs++; } ?>
    When printing the posted variables I get:

    Code:
     Array (     [helper_name] => Jo     [helper_surname] => Bloggs     [helpdays] => Array         (             [0] => Array                 (                     [day_id] => 1                     [1] => Array                         (                             [job_id] => 3                         )                      [2] => Array                         (                             [job_id] => 5                         )                      [job_time_id] => 1                     [judge] =>                      [ring_party] =>                  )              [1] => Array                 (                     [job_time_id] => 1                     [judge] =>                      [ring_party] =>                  )              [2] => Array                 (                     [job_time_id] => 1                     [judge] =>                      [ring_party] =>                  )              [3] => Array                 (                     [job_time_id] => 1                     [judge] =>                      [ring_party] =>                  )              [4] => Array                 (                     [job_time_id] => 1                     [judge] =>                      [ring_party] =>                  )              [5] => Array                 (                     [job_time_id] => 1                     [judge] =>                      [ring_party] =>                  )          )      [offer] => 1     [Submit] => Submit Helping Offer )
    From this I can see that the job_id's array is in the correct place, but still me question (and problem) is how do I serialize this nested array??

  4. #4
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    From what you are saying you have identified that its the serialize function that isn't working - if created a serialized array yourself, as you expect it to appear then it is capable of being stored in the database ... correct?

    So the problem is how do I serialize a nested (or multi or multidimensional) array.

    Dunno, never done it. (there, I am being honest ...)

    Found this on the man user notes though:
    PHP Code:
    <?php
    /*
    This is an array_walk style serialize that works with multi dimensional arrays, it also base64 encodes and decodes to allow ';' to exist in the array.
     -- Alan Reddan
    */
    $data[qwerty] = "blah";
    $data[1][a] = "1aa";
    $data[2][b] = "2bb";
    $data[3][c] = ";;;;;;";

    //To Serialise Call :

    array_walk($data,'base64_encoder_multi');
    $serialized_string serialize($data);
    //print $serialized_string . '\n'; //uncomment to see serialized array

    //To Unserialize Call

    $array unserialize($serialized_string);
    array_walk($array,'base64_cleaner_multi');

    print_r($array);
    //start functions
    function base64_encoder_multi(&$val,$key) {
       if (
    is_array($val)) array_walk($val,'base64_encoder_multi',$new);
       else {
          
    $val base64_encode($val);
       }
    }

    function 
    base64_cleaner_multi(&$val,$key) {
       if (
    is_array($val)) array_walk($val,'base64_cleaner_multi',$new);
       else {
          
    $val base64_decode($val);
       }
    }
    //ends

    ?>
    I hope that gives you a clue on how to fix it, I am not in a position to test it where I am.

    This example also deals with illegal chars that might appear in your arrays, apparantly another thing that could trip you up.

  5. #5
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    Shropshire
    Posts
    203
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for that, I sort of got it to work in that I managed to get the serialization I needed, however the input into the database then broke.

    I think I need help on the correct format of the array values in the form for the job_id's and how to utilize them properly when submitted as I really can't get my head around it at the moment.

  6. #6
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Post your serialized result, lets have a look. That serialization man page, and some old bug reports I saw when googling mentioned different chars that are causing problems ... probably need some chars escaping somewhere.

    You're using pg I see, might be an idea to post your serialized string with a really simple sql statement on the dbase forum.

    Really focus down to something like:

    "INSERT INTO shows_helpers_jobs_times ( jobs ) values ('" . $serialized ."');

    Maybe even create a temp table till you get this sorted out.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •