2

Struggling with a one page form that i want to first populate a form from a mysql query, then enable a user to update some of the values in each of several table rows from text input fields in the form.

The code's intent is to update the field by referencing the row ID.

But for some reason I'm only able to update the last row in the form (the last row from the array). I've included some troubleshooting code to see what the ID variable is and it always comes up as the last iteration of the array. I think I'm either overwriting the ID variable in the while loop or the for loop.

I have tried moving the POST/update to a 2nd file but get the same results. Any thoughts/suggestions would be greatly appreciated

Here is the code minus the db connection:

$saveClicked = $_POST["saveClicked"];


{   //  SAVE button was clicked 
    if (isset($saveClicked)) {
        unset($saveClicked);


        $ID = $_POST["ID"]; 

        $win = $_POST["Winner"];
        $winScr = $_POST["WinnerScore"];
        $losScr = $_POST["LoserScore"];         


        $tschedule_SQLupdate = "UPDATE tschedule SET ";

        $tschedule_SQLupdate .=  "Winner = '".$win."', ";
        $tschedule_SQLupdate .=  "WinnerScore = '".$winScr."', ";
        $tschedule_SQLupdate .=  "LoserScore = '".$losScr."' ";
        $tschedule_SQLupdate .=  "WHERE ID = '".$ID."' ";   


        if (mysql_query($tschedule_SQLupdate))  {   

        echo '<p> the number of mysql affected rows is '.mysql_affected_rows().'</p>';
        echo 'this is the value for post id '.$ID;

        } else {
            echo '<span style="color:red; ">FAILED to update the game.</span><br /><br />';
            echo mysql_error();

        }               
    }   
//  END:  SAVE button was clicked   ie. if (isset($saveClicked))
}


{   //  Get the details of all associated schedule records
    //      and store in array:  gameArray  with key >$indx  

        $indx = 0;

        $tschedule_SQLselect = "SELECT * ";
        $tschedule_SQLselect .= "FROM ";
        $tschedule_SQLselect .= "tschedule ";
        $tschedule_SQLselect .= "WHERE week = 1 ";

        $tschedule_SQLselect_Query = mysql_query($tschedule_SQLselect); 

        while ($row = mysql_fetch_array($tschedule_SQLselect_Query, MYSQL_ASSOC)) {

            $gameArray[$indx]['ID'] = $row['ID'];
            $gameArray[$indx]['Date'] = $row['Date'];
            $gameArray[$indx]['week'] = $row['week'];
            $gameArray[$indx]['Favorite'] = $row['Favorite'];               
            $gameArray[$indx]['Line'] = $row['Line'];
            $gameArray[$indx]['Underdog'] = $row['Underdog'];
            $gameArray[$indx]['OU'] = $row['OU'];
            $gameArray[$indx]['Winner'] = $row['Winner'];
            $gameArray[$indx]['WinnerScore'] = $row['WinnerScore'];
            $gameArray[$indx]['LoserScore'] = $row['LoserScore'];   
            $indx++;             
        }

        $numGames = sizeof($gameArray);

        mysql_free_result($tschedule_SQLselect_Query);          
}

{   //      Output 

            echo '<form name ="postGame" action="'.$thisScriptName.'" method="post">';      

                echo '<table border="1">';
                    echo '<tr>
                               <th>ID</th>
                                <th class="date">Date</th>
                                <th class="num">Week</th>
                                <th>Favorite</th>
                                <th class="num">Line</th>
                                <th>Underdog</th>
                                <th class="num">OU</th>
                                <th>Winner</th>
                                <th>WScore</th>
                                <th>LScore</th>
                                <th>Save</th>   
                            </tr>   ';  

    for ($indx = 0; $indx < $numGames; $indx++) {
    $thisID = $gameArray[$indx]['ID'];
    $saveLink = '<input type = "submit" value = "Save" />';

            $fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';

            $fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';


            echo $fld_ID;
            echo $fld_saveClicked;
                        echo '<tr>
                                    <td>'.$gameArray[$indx]['ID'].'</td>
                                    <td>'.$gameArray[$indx]['Date'].'</td>
                                    <td>'.$gameArray[$indx]['week'].'</td>
                                    <td>'.$gameArray[$indx]['Favorite'].'</td>
                                    <td>'.$gameArray[$indx]['Line'].'</td>
                                    <td>'.$gameArray[$indx]['Underdog'].'</td>
                                    <td>'.$gameArray[$indx]['OU'].'</td>
                                    <td><input type="text" size =5 name="Winner">'.$gameArray[$indx]['Winner'].'</td>
                                    <td><input type="number" size=5 name="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
                                    <td><input type="number" size=5 name="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
                                    <td>'.$saveLink.'</td>
                                </tr>   ';      

                    }

                    echo '</table>';

                echo '</form>';

echo' <a href ="../schedules/schedView.php">View Schedule</a>';     

}
edoras
  • 159
  • 3
  • 13
  • http://stackoverflow.com/questions/12020227/updating-from-mysql-to-mysqli Please update to MySQLi – Martin Jan 26 '15 at 02:49
  • I tried adding the following foreach to loop through the array, but am getting invalid argument in the foreach and struggling to understand why: – edoras Jan 26 '15 at 16:43
  • `if (isset($saveClicked)) { foreach ($_POST["ID"] as $indx => $ID)` I've also modified the variables there to: `$win = $_POST["Winner"][$indx]; $winScr = $_POST["WinnerScore"][$indx]; $losScr = $_POST["LoserScore"][$indx]; as well as the "WHERE" to $_POST['ID'][$indx]` – edoras Jan 26 '15 at 16:51

3 Answers3

3

You're using the same names for each field in each row, so when you post the form, only the last is accessible. Use array notation for the fields like this:

<input type="text" size =5 name="Winner[]">
                                       ^^

This will give you an array for $_POST['Winner'] instead of a single value. Do the same for the other <input> elements.

Also, the code that processes the form after it's submitted only processes one value. You'll need to modify that to loop through these arrays.

Warnings:

  • don't use mysql_*() for new code - it's depracated. Switch to mysqli_*() or PDO now.
  • Your code is susceptible to SQL injection. Escape your input variables with mysql_real_escape_string() (or the mysqli equivalent) or better, switch to prepared statements.
  • Thank you very much for your insight HS - did you mean that some value or variable or other should be inside the [ ]? I attempted this with the brackets empty and got a "Notice: Array to string conversion" but only the last row was updated and with just the word "Array" (for Winner). Have I missed your meaning? Also, would you be so kind as to expand on "you'll need to modify that to loop through these arrays"? fyi, I will surely be switching to mysqli and addressing security once I have it working. thanks again – edoras Jan 26 '15 at 13:26
2

After some more research I think I understand the two answers already shared much better. However I have chosen a different path and have resolved my issue -I wrapped the form tags directly around each row:

    echo '<form name ="postGame'.$indx.'" action="'.$thisScriptName.'" method="POST">';     
    $fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';   
    echo $fld_saveClicked;  
    $fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
    echo $fld_ID;               
    echo '<tr>
            <td>'.$gameArray[$indx]['ID'].'</td>
            <td>'.$gameArray[$indx]['Date'].'</td>
            <td>'.$gameArray[$indx]['week'].'</td>
            <td>'.$gameArray[$indx]['Favorite'].'</td>
            <td>'.$gameArray[$indx]['Line'].'</td>
            <td>'.$gameArray[$indx]['Underdog'].'</td>
            <td>'.$gameArray[$indx]['OU'].'</td>
            <td><input type="text" size=5 name="Winner" id="Winner">'.$gameArray[$indx]['Winner'].'</td>
            <td><input type="number" size=5 name="WinnerScore" id="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
            <td><input type="number" size=5 name="LoserScore" id="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
            <td><button type="submit" />Save</button></td>
        </tr></form>';          

                    }

One of the key trouble shooting steps was to use var_dump to validate that the $_POST actually contained data. I understand there are several ways this could be done including the responses shared by Hobo and Syed, as well as using javascript, but was really glad I could accomplish my goal with just php.

edoras
  • 159
  • 3
  • 13
-2

Your For Loop is storing the last value of the array in your form.

$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';

Store the ID value as an array in HTML form and when a form is posted get all the ID values and update using your same mysql update query.

Your winner and loser score are also returning the last array values.

  • I really appreciate your help Syed, but am very new to programming and do not understand how I can "store the ID value as an array in the html form" as you have guided. Are you suggesting something like array($ID[1]=>1, $ID[2]=>2,..etc.)? fyi, the line you referred to was only included to confirm that the id values are being generated in the form. but I feel your suggestion that the for loop is storing the last value of the array is spot on, and would greatly appreciate any further guidance you could share. – edoras Jan 26 '15 at 13:34