Jump to content


Photo

$_POST to array


  • Please log in to reply
7 replies to this topic

#1 onegative

onegative
  • Members
  • PipPip
  • Member
  • 14 posts

Posted 27 April 2006 - 12:33 PM

How am in need of help trying to understand the proper way to take my $_POST variables and build an array. Not that I do not understand the array concept, but how to do so with the following variables. My overall goal is to rebuild my UPDATE query from my form...this is my very first php application thus please overlook my ignorance.

Here is a sample of the $_POST key => value pairs:

266~StarTrac = 77701
266~Recipient = dg4305
266~RepeatPage = 1
266~RepeatTime = 1800
266~BlkOutPeriod = 00:00-07:00
267~StarTrac = 76001
267~Recipient = wh3275
267~RepeatPage = 1
267~RepeatTime = 1800
267~BlkOutPeriod = 00:00-07:00
268~StarTrac = 74001
268~Recipient = th5299
268~RepeatPage = 1
268~RepeatTime = 1800
268~BlkOutPeriod = 00:00-07:00

The problem is that the starting numeric value is my ID for the table record, I attached it to the INPUT form name so I could carry the ID with each field from the form. I am UPDATING many fields simultanously from a single form...and I am unsure how to do this properly.

What I am looking to get is the data into the following array format from the $_POST key => value pairs.

266 77701 dg4305 1 1800 00:00-07:00
267 76001 wh3275 1 1800 00:00-07:00
268 74001 th5299 1 1800 00:00-07:00

and so on...

The direction I am leaning is to use the following code to process the $_POST query string:

foreach ($_POST as $key=>$value):
     $parts = explode("~", $key);
     $base = array($parts[0],$parts[1] = $value);
     print "<pre>";
     print_r($base);
     print "</pre>";
endforeach;

Which results in the following array data:

Array
(
[0] => 266
[1] => 77701
)

Array
(
[0] => 266
[1] => dg4305
)

Array
(
[0] => 266
[1] => 1
)

Array
(
[0] => 266
[1] => 1800
)

Array
(
[0] => 266
[1] => 00:00-07:00
)

Array
(
[0] => 267
[1] => 76001
)

Array
(
[0] => 267
[1] => wh3275
)

Array
(
[0] => 267
[1] => 1
)

Array
(
[0] => 267
[1] => 1800
)

Array
(
[0] => 267
[1] => 00:00-07:00
)

Array
(
[0] => 268
[1] => 74001
)

Array
(
[0] => 268
[1] => th5299
)

Array
(
[0] => 268
[1] => 1
)

Array
(
[0] => 268
[1] => 1800
)

Array
(
[0] => 268
[1] => 00:00-07:00
)


But now that I have the array I am not sure how to reference it to extract the data. This is where I am stuck...


Any and all suggestions would be greatly appreciated.
Thanks,
Danny

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 27 April 2006 - 01:07 PM

The first question I have is what do you want to do with the data? It's unclear from your description.

Also, can you post the script that generates your form. There may be a better way of POSTing your data back to your script.

Ken

#3 onegative

onegative
  • Members
  • PipPip
  • Member
  • 14 posts

Posted 27 April 2006 - 01:28 PM

OK, I have a form that is created and populated with data from a SQL query. The reason for the form data was to create a way to update multiple fields. So once I build the form, then I want to be able to modify fields of that form. Then I perform a test to see if it is an update, if an update I then process the $_POST query string but I need to use it to perform an UPDATE to the database. I did not want to perform an UPDATE on each row, but rather create an array and then loop the array to update the rows.

Here is the code thus far, again this is my first php I have ever written so its formatting and/or shortcuts my not be of a caliber that a php guru would approve. But I thank you very much for your help and/or suggestions in learning how to understand its proper usage...

DannyG

<?php

// Includes Required
include 'db.php';
include 'sessionChk.php';

// Session starter and session verifier
session_start();
session_checker();

?>

<form method="post" action="<?php echo $PHP_SELF?>">

<?php

// Welcome message displaying registered session info
echo "Welcome ". $_SESSION['first_name'] ." ". $_SESSION['last_name'] ."!<br /><br />";


// If the call to this form is from notifications.php use this path
if($_POST[Arraybox]){
        // Message indicating which host is being queried
        $hostname =  $_POST[Arraybox];
        echo "<H3>$hostname</H3><BR />";

        // Initial SELECT against host selected
        $sql = mysql_query("SELECT * FROM patHost,patAlertGroup,patAlert WHERE HostName='$hostname' AND patHost.HOST_ID=patAlertGroup.HOST_ID AND patAlertGroup.ALERTGROUP_ID=patAlert.ALERTGROUP_ID");

        // Building table headers
                echo "<table>
        <tr>
                <td><b>AlertGroup</b></td>
                <td><b>StarTrac</b></td>
                <td><b>Recipient</b></td>
                <td><b>RepeatPage</b></td>
                <td><b>RepeatTime</b></td>
                <td><b>BlkOutPeriod</b></td>
        </tr>";

                // Alternate colors for table rows
                $color1 = "#CCFFCC";
                $color2 = "#BFD8BC";

                // Row color starter for modulus
                $row_count = 0;

                //  Looping through sql results and building php array
                while ($row = mysql_fetch_array($sql)){
                $alertgroup[] = $row[AlertGroup].":".$row[StarTrac].":".$row[Recipient].":".$row[RepeatPage].":".$row[RepeatTime].":".$row[BlkOutPeriod].":".$row[ALERTGROUP_ID];
                }
        foreach($alertgroup as $key=>$value):
                list($ag, $startrac, $recipient, $repeatpage, $repeattime, $blkoutperiod,$a
gid) = split(":", $value, 7);
                $row_color = ($row_count % 2) ? $color1 : $color2;
                echo "<tr>
            <td bgcolor=\"$row_color\">$ag</td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"$agid~StarTrac\" value=\"$startrac\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"$agid~Recipient\" value=\"$recipient\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"$agid~RepeatPage\" value=\"$repeatpage\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"$agid~RepeatTime\" value=\"$repeattime\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"$agid~BlkOutPeriod\" value=\"$blkoutperiod\"></td>
            </tr>";
            $row_count++;
        endforeach;
                echo "</table>";
}
// If the call to this form is from PHP SELF use this path
else{

        foreach ($_POST as $key=>$value):
                //echo $key . " " . "=" . " " . $value;
                //echo "<BR/>";
                $parts = explode("~", $key);
                $base = array($parts[0]=>array($parts[1], $value));
                print "<pre>";
                print_r($base);
                print "</pre>";
        endforeach;
}


?>



#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 27 April 2006 - 03:42 PM

For someone who's new to PHP, your code is very easy to read and indented very well. I do have some suggestions:
  • Whenever you use a literal index to an array surround it with quotes. i.e. instead of $_POST[xyz], you should write $_POST['xyz'] or $_POST["xyz"]
  • Instead of
    <?php if($_POST[Arraybox]) ?>
    use
    <?php if (isset($_POST['Arraybox'])) ?>
  • Since you're referencing the data returned from the database with the field names, you should use "mysql_fetch_assoc()" instead of "mysql_fetch_array()".
I dont see the <input> tag for the Submit Button or the closing </form> tag.

You should be able to use an array for the names of your input fields, perhaps something like:
<td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][StarTrac]\" value=\"$startrac\"></td>
The resultant array that is returned to your script in the $_POST array would look something like:
Array
(
    [266] => Array
        (
            [StarTrac] => 77701
            [Recipient] => dg4305
            [RepeatPage] => 1
            [RepeatTime] => 1800
            [BlkOutPeriod] => 00:00-07:00
        )

    [267] => Array
        (
            [StarTrac] => 76001
            [Recipient] => wh3275
            [RepeatPage] => 1
            [RepeatTime] => 1800
            [BlkOutPeriod] => 00:00-07:00
        )

    [268] => Array
        (
            [StarTrac] => 74001
            [Recipient] => th5299
            [RepeatPage] => 1
            [RepeatTime] => 1800
            [BlkOutPeriod] => 00:00-07:00
        )

)
It would be processed with something like:
<?php
foreach($info as $id => $fields) {
    echo 'ID: ' . $id . "\n";
    foreach ($fields as $k => $v) {
        echo '>>>>>' . $k . ' = ' . $v . "\n";
    }
}
?>

I hope I've made sense...

Ken

#5 onegative

onegative
  • Members
  • PipPip
  • Member
  • 14 posts

Posted 27 April 2006 - 04:41 PM

By the way, thank you bvery, very much for your help. I truly appreciate you giving time to this. Well most of this made sense, I see the logic in using an array for the form name, but I am a little confused about how it would be extracted from the $_POST query string. I had made modifications as you suggested to the script, as far as the submit and form tag they were outside the <?php ?> tags so I didn't include them but I have included the entire file at the bottom..

The thing that has me confused is if I do indeed use the follow code and set the field name to an array as such:


<td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][StarTrac]\"
value=\"$startrac\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][Recipient]\"
 value=\"$recipient\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][RepeatPage]\
" value=\"$repeatpage\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][RepeatTime]\
" value=\"$repeattime\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][BlkOutPeriod
]\" value=\"$blkoutperiod\"></td>



Why does the my $_POST loop only return the following? Is the info = Array indicating there is an array there?


Welcome Danny Gibson!

info = Array
hostname = tspform01
update = Update information

The $_POST loop I am using is:

        foreach ($_POST as $key=>$value):
                echo $key . " " . "=" . " " . $value;
                echo "<BR/>";
        endforeach;


I have included the entire php file in hopes you will see where I have gone astray:

<html>
<head>
<title>Update Notifications</title>
</head>
<body>

<?php

// Includes Required
include 'db.php';
include 'sessionChk.php';

// Session starter and session verifier
session_start();
session_checker();

?>

<form method="post" action="<?php echo $PHP_SELF?>">

<?php

// Welcome message displaying registered session info
echo "Welcome ". $_SESSION['first_name'] ." ". $_SESSION['last_name'] ."!<br /><br />";


// If the call to this form is from notifications.php use this path
if (isset($_POST['Arraybox'])){
        // Message indicating which host is being queried
        $hostname =  $_POST['Arraybox'];
        echo "<H3>$hostname</H3><BR />";

        // Initial SELECT against host selected
        $sql = mysql_query("SELECT * FROM patHost,patAlertGroup,patAlert WHERE HostName='$hostname' AND patHost.HOST_ID=patAlertGroup.HOST_ID AND patAlertGroup.ALERTGROUP_ID=patAlert.ALERTGROUP_ID");

        // Building table headers
                echo "<table>
        <tr>
                <td><b>AlertGroup</b></td>
                <td><b>StarTrac</b></td>
                <td><b>Recipient</b></td>
                <td><b>RepeatPage</b></td>
                <td><b>RepeatTime</b></td>
                <td><b>BlkOutPeriod</b></td>
        </tr>";

                // Alternate colors for table rows
                $color1 = "#CCFFCC";
                $color2 = "#BFD8BC";

                // Row color starter for modulus
                $row_count = 0;

                //  Looping through sql results and building php array
                while ($row = mysql_fetch_assoc($sql)){
                $alertgroup[] = $row[AlertGroup].":".$row[StarTrac].":".$row[Recipient].":".$row[RepeatPage].":".$row[RepeatTime].":".$row[BlkOutPeriod].":".$row[ALERTGROUP_ID];
                }
        foreach($alertgroup as $key=>$value):
                list($ag, $startrac, $recipient, $repeatpage, $repeattime, $blkoutperiod,$agid) = split(":", $value, 7);
                $row_color = ($row_count % 2) ? $color1 : $color2;
                echo "<tr>
            <td bgcolor=\"$row_color\">$ag</td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][StarTrac]\"value=\"$startrac\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][Recipient]\" value=\"$recipient\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][RepeatPage]\" value=\"$repeatpage\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][RepeatTime]\" value=\"$repeattime\"></td>
            <td bgcolor=\"$row_color\"><input type=\"text\" name=\"info[$agid][BlkOutPeriod]\" value=\"$blkoutperiod\"></td>
            </tr>";
            $row_count++;
        endforeach;
                echo "</table>";
}
// If the call to this form is from PHP SELF use this path
else{

        foreach ($_POST as $key=>$value):
                echo $key . " " . "=" . " " . $value;
                echo "<BR/>";
        endforeach;


}

echo "<input type=\"Hidden\" name=\"hostname\" value=$hostname>";
echo "<BR/>";
?>
<center>
<input type="Submit" name="update" value="Update information">
</center>
</form>
</body>
</html>


#6 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 27 April 2006 - 05:41 PM

The best way to see what's in the $_POST array, or any array for that matter, is to use something like this:
<?php echo '<pre>' . print_r($_POST,true) . '</pre>'; ?>
The echo command doesn't know how to deal with arrays.


One thing I forgot to mention in my last post. Your method of generating the <input> tags can be improved. What follows is the way I would do it and since I do not like using an echo that goes over many lines, I use a temporary array to store everything that would normally be echoed and echo the imploded array at the end:
<?php
               $tmp = array();
                while ($row = mysql_fetch_assoc($sql)){
                    $row_color = ($row_count % 2) ? $color1 : $color2;
                    $tmp[] = '<tr>';
                    $tmp[] = '<td bgcolor="' . $row_color . '">' . $row['ag'] . '</td>';
                    $tmp[] = '<td bgcolor="' . $row_color . '"><input type="text" name="info[' . $row['agid'] . '][StarTrac]" value="' . $row['StarTrac'] . '"></td>';
                    $tmp[] = '<td bgcolor="' . $row_color . '"><input type="text" name="info[' . $row['agid'] . '][Recipient]" value="' . $row['Recipient'] . '"></td>';
                    $tmp[] = '<td bgcolor="' . $row_color . '"><input type="text" name="info[' . $row['agid'] . '][RepeatPage]" value="' $row[RepeatPage'] . '"></td>';
                    $tmp[] = '<td bgcolor="' . $row_color . '"><input type="text" name="info[' . $row['agid'] . '][RepeatTime]" value="' . $row['RepeatTime'] . '"></td>';
                    $tmp[] = '<td bgcolor="' . $row_color . '"><input type="text" name="info[' . $row['agid'] . '][BlkOutPeriod]" value="' . $row[]'BlkOutPeriod'] . '"></td>';
                    $tmp[] = '</tr>";';
                    $row_count++;
                }
               echo implode("\n",$rmp)."\n";
?>


Ken


#7 onegative

onegative
  • Members
  • PipPip
  • Member
  • 14 posts

Posted 27 April 2006 - 06:55 PM

Hey Ken,

I have learned a lot of stuff today. Your suggestions have been taken to heart. I really see the benefit of using an array in the form's field name especially when the form contain as much as a 1000 fields. That was a killer idea...

Also thanks for pointing out the finer points of using the proper syntax on some of the smaller items.

I took your advice and used the tmp array to manage the table rows and then impolde them to the page, again an outstanding use of an array, I will definately use this technique going forward as I learn more about php. There were small changes required as I had to use the actual row names from the table as well as a couple small syntax related changes but it is working like a champ.

And you were correct about using the:
echo '<pre>' . print_r($_POST,true) . '</pre>';
As I can now see the array data...

Array
(
[info] => Array
(
[1] => Array
(
[StarTrac] => 77701
[Recipient] => dg4305
[RepeatPage] => 1
[RepeatTime] => 1800
[BlkOutPeriod] => 00:00-07:00
)

[2] => Array
(
[StarTrac] => 76601
[Recipient] => wh3275
[RepeatPage] => 1
[RepeatTime] => 1800
[BlkOutPeriod] => 00:00-07:00
)
and so on...


As a final request that I believe will help me understand the complete aspect of using an array being passed through the $_POST is "How do I actually get to array data?"

I attempted to use the snipet of code you provided but I am unsure how to grab the array from the $_POST query string...nothing jumps out to me as obvious...my quess is I have to parse the $_POST somehow before using this snipet of code????


foreach($info as $id => $fields) {
     echo 'ID: ' . $id . "\n";
     foreach ($fields as $k => $v) {
          echo '>>>>>' . $k . ' = ' . $v . "\n";
     }
}

Again many thanks for the lesson, it has been great...and I would completely understand if you can not help me further, regardless you have been very kind and I do appreciate the help.

Danny


#8 onegative

onegative
  • Members
  • PipPip
  • Member
  • 14 posts

Posted 27 April 2006 - 07:07 PM

Hey Ken,

I just saw it....

$info=$_POST['info'];

That builds my array into the current namespace so I can access it....

Whoooo Hoooooo!

Many thanks and have a great day,
Danny




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users