Problem with 2D $_POST array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Problem with 2D $_POST array

Post by JustPlainJef »

Howdy again.

Still fighting with my array. Here's a little background if it will help.

viewtopic.php?f=1&t=126284

viewtopic.php?f=1&t=126542

I also don't have all of my code with me, but I have a few samples...

Basically, I'm trying to collect some information for a 2D array. I have a schedule for a softball league, and I'm trying to re-schedule games that get marked as "postponed." Here's the easy way to see the data...
Image

There's also a checkbox on the far right, and a hidden field with a game number on the left.

Here's how I setup my table. (Yes, I know I didn't choose the best field names, but I'm no where near production. When I go to production, I'll have better field names. :oops: )

Code: Select all

$i=0;	
while($row = mysqli_fetch_assoc($result))   $result is the SQL query of the games on a date that may need to be postponed
      {
 extract ($row);   #Pulls result, one row at a time
	 $f_Date = date("F j", strtotime($Date));     #Formats date and time
	 $f_Time = date("g:i A", strtotime($Time));
	 echo "<input type = 'hidden' name = 'Number[$i]' value = '$Number' />
		 <tr>\n
		 <td align='center'><input type = 'hidden' name = 'Date[$i]' value = '$Date' />$f_Date</td>
		<td align='center'><input type = 'hidden' name = 'Time[$i]' value = '$Time' />$f_Time</td>
		<td align='center'><input type = 'hidden' name = 'Field[$i]' value = '$Field' />$Field</td>
		<td align='center'><input type = 'hidden' name = 'Division[$i]' value = '$Division' />$Division</td>
		<td align='center'><input type = 'hidden' name = 'AwayColor[$i]' value = '$AwayColor' />$AwayColor</td>
		<td align='center'><input type = 'hidden' name = 'AwayManager[$i]' value = '$AwayManager' />$AwayManager</td>
		<td align='center'><input type = 'hidden' name = 'HomeColor[$i]' value = '$HomeColor' />$HomeColor</td>
		 <td align='center'><input type = 'hidden' name = 'HomeManager[$i]' value = '$HomeManager' />$HomeManager</td>
		 <td align='center'><input type='checkbox' name='rain[$i]' /></td>
	 </tr>\n";
	$i++;
	}
  echo "</table><BR /><BR />\n
	<input type='submit' value='Postpone Selected Games'>
	</form>";			#Submit button
When I run this, the array is "backwards." it comes out like this... (I put it in code brackets to shrink it)

Code: Select all

Array
(
    [Number] => Array
        (
            [0] => 103
            [1] => 108
            [2] => 107
            [3] => 106
            [4] => 102
            [5] => 100
            [6] => 101
            [7] => 99
            [8] => 105
            [9] => 104
            [10] => 109
            [11] => 110
        )

    [Date] => Array
        (
            [0] => 2011-01-21
            [1] => 2011-01-21
            [2] => 2011-01-21
            [3] => 2011-01-21
            [4] => 2011-01-21
            [5] => 2011-01-21
            [6] => 2011-01-21
            [7] => 2011-01-21
            [8] => 2011-01-21
            [9] => 2011-01-21
            [10] => 2011-01-21
            [11] => 2011-01-21
        )

    [Time] => Array
        (
            [0] => 18:00:00
            [1] => 18:00:00
            [2] => 18:00:00
            [3] => 18:00:00
            [4] => 18:00:00
            [5] => 18:00:00
            [6] => 18:00:00
            [7] => 18:00:00
            [8] => 18:00:00
            [9] => 18:00:00
            [10] => 20:00:00
            [11] => 20:00:00
        )

etc etc etc
I think it would be better to reverse the array, have it more like

Code: Select all

Array
(
    [0] => Array
        (
            [Number] => 103
            [Date] => 2011-01-21
            [Time] => 10:00:00
            [Field] => PP3
            etc etc etc.....
        )
    [1] => Array
        (
            [Number] => 105
            [Date] => 2011-01-21
            [Time] => 10:00:00
            [Field] => FR2
            etc etc etc.....
        )

My end goal, at least at this page update, is to be able to put the games that are postponed into a new table, and check the box for the "Rainout" in the main schedule table. I'm not sure how to pull the data from the array as I have it. I was planning on using a double "FOR EACH" loop to make the updates, similar to creating a table from a 2D array, but as it stands right now, when I output to a table, instead of a line for each game, it's a column for each game..... Please help...

I tried reversing the data on my table, going from <input type = 'hidden' name = 'Date[$i]' value = '$Date' /> to <input type = 'hidden' name = '$i[Date]' value = '$Date' />, but to no avail.... I got nothing in the array when I did that...
User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: Problem with 2D $_POST array

Post by Jade »

I'm not exactly sure what you're doing or what problems you're having but from what I can understand you're not getting the correct structure in your array. Here's some psuedocode that may help:

Code: Select all

$gameArray = array();
$index = 0;
$loop = mysql_query(select your list of games) or die (mysql_error());

while ($row = mysql_fetch_array($loop))
{
   //for each game you need to add the following information into your array
    $gamesArray[$index]["field"] = $row['field'];
    $gamesArray[$index]["date"] = $row['date'];
    $gamesArray[$index]["time"] = $row['time'];
   
   $index++;
}

print_r($gamesArray);

JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

The problem is that I'm using the $_POST array, so it's pulling the data from a form.

I will try putting [brackets] around both the index and the field name.
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

<input type = 'hidden' name = '[Date][$i]' value = '$Date' />

That did not work. $_POST array came back empty...

Let me start from the beginning again...

I've got the test site up and functioning somewhat. There's an administrative login where people get some options of items to modify. One of them would be the schedule. Let's say it rains today (not likely at -2F, but hey, let's think Spring!) and we have to cancel the late games. The 6PM games got played, the 8PM games are postponed. So Joe Board Member logs in and goes to the schedule update page. The page defaults to today's games, as most likely we won't cancel the games until that day, but I do have a box to select another date. Then they see this....
Image

What I want is to be able to select multiple check boxes and send that data to the next page. I haven't exactly figured out my insert query, as I think I want to keep the old date and allow the change to be reviewed before it's submitted.
(Junior game on January 21 between White and Blue will be rescheduled from 8 PM on Petersen Park 3 to January 22, 4PM, Fox Ridge 2)
However, I can't even get the $_POST array to be readable to a point where I'm familiar with it.

What I think I'd like to see is:

Code: Select all

Array
(
    [0]=> Array
        (
            [Number] => 103
            [Date] => 2011-01-21
            [Time] => 20:00:00
            [Field] => Petersen Park 3
            [Division] => Junior
            [AwayColor] => White
            [AwayManager] => Williams
            [HomeColor] => Blue
            [HomeManager] => Bell
            [rain] => on
        )

      [1]=> Array
        (
            [Number] => 105
            [Date] => 2011-01-21
            [Time] => 20:00:00
            [Field] => Petersen Park 4
            [Division] => Instructional
            [AwayColor] => Mint
            [AwayManager] => Martin
            [HomeColor] => White
            [HomeManager] => Walker
            [rain] => on
        )
etc etc etc
I know there would be more fields with [rain] set to off, but those I could filter out...

Thanks again Jade!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Problem with 2D $_POST array

Post by John Cartwright »

A little busy so I've just skimmed your thread, but if all your looking to do is convert your array into this new format, then you could do something like

Code: Select all

$items = count($_POST['Numbers']); 
$newarray = array();

for ($x=0; $x<$items; $x++) 
{
   $newarray[] = array(
      'Number' => $_POST[$x]['Numbers'],
      'Date' => $_POST[$x]['Date'],
      'Time' => $_POST[$x]['Time']
   );
}

echo '<pre>'. print_r($newarray, true) .'</pre>';
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Problem with 2D $_POST array

Post by gooney0 »

I would suggest taking a step backwards and deciding on the layout of your array first.

Here is how I would approach this:

Decide on the layout of your array. Perhaps something like:

$games[$number]["Date"]
$games[$number]["Time"]
$games[$number]["Field"]

Now code your output and queries to use the same format. You may want to write some simple db functions to speed up this process.

I have functions like:

$data=db_get_indexed_array($table, $fields, $where, $sort);

Once written I never have to think about it again.
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

If I put it into an array on that page, how would I pass it onto the next page on a form? I want it so that the user can edit some data, then pass it along.
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

Let's take it a step simpler.

Let's say you were designing a sight where people could enter what they wore... 7 sets of text boxes, shirt, pants, shoes. If they filled in 3, it would add three. If they filled in 7, it would add 7. How would you do something like that, and would it be with $_POST?

<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />
<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />
<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />
<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />
<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />
<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />
<input type = 'text' name = 'pants' /><input type = 'text' name = 'shirt' /><input type = 'text' name = 'shoes' />

If this were your form, and going into $_POST, how would you name the fields?
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Problem with 2D $_POST array

Post by gooney0 »

I would name those fields:

rows[$rownumber]["pants"]
rows[$rownumber]["shirt"]
rows[$rownumber]["shoes"]

To work with it i'd use:

foreach($rows as $row)
{
// print a table row of inputs or Update the DB

}

Keep in mind input names need to start with letters. javascript won't use numbers.
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

gooney0 wrote:I would name those fields:

rows[$rownumber]["pants"]
rows[$rownumber]["shirt"]
rows[$rownumber]["shoes"]

To work with it i'd use:

foreach($rows as $row)
{
// print a table row of inputs or Update the DB

}

Keep in mind input names need to start with letters. javascript won't use numbers.
OK. That's what I'm looking for, but since I'm using $_POST, I'm not sure I can set my array as I want it. However..... Your last line gives me something to try tomorrow morning! I'm not using javascript, but I'll try anything at this moment...
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

I GOT IT!!! Drinks on me... :drunk:

First set of code, where you check the postponed games... Simple table based off of an SQL array. Table defaults to today's date, but user can change that.

Code: Select all

<?php
#create the table data
$i=0;
while($row = mysqli_fetch_assoc($result))
        {
        extract ($row);
        $f_Date = date("F j", strtotime($Date));
        $f_Time = date("g:i A", strtotime($Time));
        echo "<input type = 'hidden' name = 'Game[$i][Number]' value = '$Number' />
        <tr>
        <td align='center'><input type = 'hidden' name = 'Game[$i][Date]' value = '$Date' />$f_Date</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][Time]' value = '$Time' />$f_Time</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][Field]' value = '$Field' />$Field</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][Division]' value = '$Division' />$Division</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][AwayColor]' value = '$AwayColor' />$AwayColor</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][AwayManager]' value = '$AwayManager' />$AwayManager</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][HomeColor]' value = '$HomeColor' />$HomeColor</td>
        <td align='center'><input type = 'hidden' name = 'Game[$i][HomeManager]' value = '$HomeManager' />$HomeManager</td>
        <td align='center'><input type='checkbox' name='Game[$i][rain]' /></td>
        </tr>";
        $i++;
        }
echo "</table><BR /><BR />
<input type='submit' value='Postpone Selected Games'></form>";#Submit button
?>
The key was the game[$i][$variable]. I think it has an extra dimension to the array that I don't need, but I'll take it... I was unable to do Game$i as as array... Here's (part of) my array, showing unchecked and checked results... I cut out 1 - 7 and put it in PHP tags to conserve space...

Code: Select all

Array
(
    [Game] => Array
        (
            [0] => Array
                (
                    [Number] => 178
                    [Date] => 2011-01-24
                    [Time] => 18:00:00
                    [Field] => Duker Instructional
                    [Division] => Instructional
                    [AwayColor] => Green
                    [AwayManager] => Garcia
                    [HomeColor] => Purple
                    [HomeManager] => Parker
                )

            [8] => Array
                (
                    [Number] => 183
                    [Date] => 2011-01-24
                    [Time] => 18:00:00
                    [Field] => Petersen Park 4
                    [Division] => Senior
                    [AwayColor] => Silver
                    [AwayManager] => Smith
                    [HomeColor] => Mint
                    [HomeManager] => Mitchell
                    [rain] => on
                )

            [9] => Array
                (
                    [Number] => 184
                    [Date] => 2011-01-24
                    [Time] => 18:00:00
                    [Field] => Petersen Park 5
                    [Division] => Senior
                    [AwayColor] => Mint
                    [AwayManager] => Mitchell
                    [HomeColor] => Red
                    [HomeManager] => Rodriguez
                    [rain] => on
                )

            [10] => Array
                (
                    [Number] => 185
                    [Date] => 2011-01-24
                    [Time] => 20:00:00
                    [Field] => Petersen Park 3
                    [Division] => Instructional
                    [AwayColor] => Silver
                    [AwayManager] => Sanchez
                    [HomeColor] => White
                    [HomeManager] => Walker
                )

            [11] => Array
                (
                    [Number] => 186
                    [Date] => 2011-01-24
                    [Time] => 20:00:00
                    [Field] => Petersen Park 4
                    [Division] => Pony
                    [AwayColor] => Green
                    [AwayManager] => Green
                    [HomeColor] => Purple
                    [HomeManager] => Price
                )

        )

)
Finally, the MySQL update. This only runs when the check mark has been flagged...

Code: Select all

<?php
$i = 0;
foreach($_POST as $array)
        {
        foreach($array as $game)
                {
                IF($game['rain']=='on')
                        {
                        $sqlupdate = "UPDATE schedule SET Rainout = '1' WHERE 
                        Date = '$game[Date]' AND Time = '$game[Time]' AND Field = '$game[Field]'";
                        $sqlinsert = "INSERT INTO postponed 
                                        values (
                                        '$game[Number]', 
                                        '$game[Date]', 
                                        '$game[Date]', 
                                        '$game[Time]', 
                                        '$game[Time]', 
                                        '$game[Field]', 
                                        '$game[Field]', 
                                        '$game[Division]', 
                                        '$game[AwayColor]', 
                                        '$game[AwayManager]', 
                                        '$game[HomeColor]', 
                                        '$game[HomeManager]')";
                        IF(!$update = mysqli_query($cxn, $sqlupdate))
                           die ("Couldn't update record.");
                        IF(!$insert = mysqli_query($cxn, $sqlinsert))
                           die ("Couldn't insert record.");
                        $i++;
                        }
                }
        }
echo "$i games updated.";
?>
Again, I made a new table so I could add newDate newTime and newField so I can use "Game at $Date $Time $Field will be rescheduled to $newDate $newTime $newField" and allow the users to review the info before they submit it. That's why $Date $Time and $Field are being inserted twice. newVar will default to Var. This will allow my updates to be posted on something like "If (Date != newDate OR Time != newTime OR Field != newField)." In this way, if the user doesn't change anything, nothing happens.

But I'm also changing the Rain flag to 1 in the primary schedule table so that I could also run it without the second table... I'm also debating adding a schedule showing what games were postponed and have yet to be re-scheduled, but I'm not sure on the value.

Ideas are always welcome. I'll probable pop this into the code forum in a week or so to get some additional feedback.
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Problem with 2D $_POST array

Post by gooney0 »

Glad to hear it's working. :D

The work you've done here is something you'll find yourself doing many times. Now would be a good time to go back through your code and create some generic functions or a class.

Example:

You could have a generic function that assumes each of the keys is a field name in your table and does updates.

// This isn't complete code. You'll need to clean it up and add things to it

function update_from_array($array)
{
foreach($array as $row)
{
// do an update query with "Number" == $row["Number"]
foreach(array_keys($row) as $key)
{
$query.=" {$key} = {$row[$key]} ";
$query.=" , ";
}
$query.=" WHERE `Number` = \"{$row["Number"]}\"
}
// run the query, and get the status
return $status;
}

Once complete these functions really pay dividends. I can't remember the last time I used a mysql_ function. I just use my generic function instead.
JustPlainJef
Forum Commoner
Posts: 42
Joined: Tue Jan 04, 2011 5:04 am
Location: McHenry, IL

Re: Problem with 2D $_POST array

Post by JustPlainJef »

That's certainly some good advice! I'll look into creating and storing the functions somewhere here soon... I do know that I've typed in the one to make a table from an SQL query a fwe times now, but it's all been copy / paste, with a few tweaks here and there. So it hasn't been horrible yet... But yeah, functions is on my "to learn more about" list.
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Problem with 2D $_POST array

Post by gooney0 »

Some more tips on how I like to start projects.

I copy some files i've already created:

include/start.php (This file includes other files for every page in the project)
include/functions_generic.php (This file has purely generic functions I can safely use in any project)
include/functions.php (Specific functions to this project. Not likely relevant to other projects)

When I add things to functions_generic.php or make improvements I can safely copy them to other projects.

This is great for things like:

formatting a number into dollars (10000 is returned as $10,000.00)

Validate a "First Name" return true or false
Post Reply