PHP page won't update mysql record

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stantron
    New Member
    • Jan 2008
    • 5

    PHP page won't update mysql record

    Setup: I only have one database with one table in it. The first page has a form that adds a record (w/ 6 fields in it) to the mySQL database's lone table via PHP. This works fine. I also have a PHP table that displays all records in my database on this same page. This too works fine. I have my table set up so that there is a 7th field, called "rid" to act as a "record id" or unique identifying field. This is primary and auto-incremented. There is a second form on the same page that prompts the user to enter a "rid". One this form is submitted it loads a second PHP page that displays the fields of whichever record was specified by the "rid" and allows the user to edit them.

    Problem: When this second PHP page's form is submitted, a third PHP page is supposed to UPDATE the mySQL table. It... doesn't, despite echoing that is has.

    Second Page Code:
    [code=php]
    <?php
    error_reporting (E_ALL);
    ini_set('displa y_errors', true);
    foreach($HTTP_P OST_VARS as $varname => $value)
    $formVars[$varname]=$value;
    $db1=mysql_conn ect("XXXXX","XX XXXXX","XXXXXXX ");
    mysql_select_db ("tracking") ;
    $query="SELECT * FROM job_status WHERE rid = \"".$formVar s["rid"]."\"";
    $result=mysql_q uery($query);
    $row=mysql_fetc h_array($result );
    $formVars = array();
    $formVars["bone"]=$row["bone"];
    $formVars["ctwo"]=$row["ctwo"];
    $formVars["lthree"]=$row["three"];
    $formVars["rfour"]=$row["rfour"];
    $formVars["ifive"]=$row["ifive"];
    $formVars["fsix"]=$row["fsixl"];
    $formVars["rid"]=$row["rid"];
    mysql_close($db 1);
    ?>
    <html>
    <head>
    <title>Job Status Update</title>
    </head>
    <body bgcolor="white" >
    <form method="post" action="page3.p hp">
    <table>
    <col span="1" align="right">
    <tr>
    <td><font color="blue">Bo ne:</font></td>
    <td><input type="text" name="bone"
    value="<? echo $formVars["bone"]; ?>" size=100></td>
    </tr>
    <tr>
    <td><font color="blue">Ct wo:</font></td>
    <td><input type="text" name="ctwo"
    value="<? echo $formVars["ctwo"]; ?>" size=100></td>
    </tr>
    <tr>
    <td><font color="blue">Lt hree:</font></td>
    <td><input type="text" name="lthree"
    value="<? echo $formVars["lthree"]; ?>" size=100></td>
    </tr>
    <tr>
    <td><font color="blue">Rf our:</font></td>
    <td><input type="text" name="rfour"
    value="<? echo $formVars["rfour"]; ?>" size=100></td>
    </tr>
    <tr>
    <td><font color="blue">If ive:</font></td>
    <td><input type="text" name="ifive"
    value="<? echo $formVars["ifive"]; ?>" size=100></td>
    </tr>
    <tr>
    <td><font color="blue">Fs ix:</font></td>
    <td><input type="text" name="fsix"
    value="<? echo $formVars["fsix"]; ?>" size=100></td>
    </tr>
    <tr>
    <td><font color="blue">ri d:</font></td>
    <td><input type="text" name="rid"
    value="<? echo $formVars["rid"]; ?>" size=100></td>
    </tr>
    <tr>
    </tr>
    <tr>
    <td><input type="submit" value="Submit"> </td>
    </tr>
    </body>
    </html>
    [/code]
    Third Page Code:
    [code=php]
    <html>
    <head>
    <title>Job Status Updated</title>
    </head>
    <body bgcolor="white" >
    <?php
    foreach($HTTP_P OST_VARS as $varname => $value)
    $formVars[$varname]=$value;
    $db1=mysql_conn ect("XXXXXX","X XXXXX","XXXXXX" );
    mysql_select_db ("tracking") ;
    echo "Record updated<br><a href=\"tracking .php\">click here</a> to update another record<br>";
    $query="UPDATE job_status set ".
    "bone= \"".$formVar s["bone"]."\",".
    "ctwo= \"".$formVar s["ctwo"]."\",".
    "lthree= \"".$formVar s["lthree"]."\",".
    "rfour= \"".$formVar s["rfour"]."\",".
    "ifive= \"".$formVar s["ifive"]."\",".
    "fsix= \"".$formVar s["fsix"]."\",".
    "\" WHERE rid = \"".$formVar s["rid"]."\"" or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');
    mysql_query($qu ery);
    mysql_close($db 1);
    ?>
    </body>
    </html>
    [/code]
    (I've removed the mysql_connect values from the code. I don't think the first page's code needs to be included as everything is passed perfectly fine from the first to the second and everything works fine on that page)

    Can anyone provide any pointers on what I'm messing up? I'm new to PHP and I feel like I've made some dumb typo but just can't see it. (The table will update in PHPadmin perfectly fine)
    Last edited by Atli; Jan 26 '08, 04:12 AM. Reason: Added [code] tags.
  • brettl
    New Member
    • Sep 2007
    • 41

    #2
    I don't think you need the foreach($HTTP_P OST_VARS as $varname => $value).

    Read here about Predefined Variables .

    Comment

    • stepterr
      New Member
      • Nov 2007
      • 157

      #3
      Originally posted by stantron
      Setup: I only have one database with one table in it. The first page has a form that adds a record (w/ 6 fields in it) to the mySQL database's lone table via PHP. This works fine. I also have a PHP table that displays all records in my database on this same page. This too works fine. I have my table set up so that there is a 7th field, called "rid" to act as a "record id" or unique identifying field. This is primary and auto-incremented. There is a second form on the same page that prompts the user to enter a "rid". One this form is submitted it loads a second PHP page that displays the fields of whichever record was specified by the "rid" and allows the user to edit them.

      Problem: When this second PHP page's form is submitted, a third PHP page is supposed to UPDATE the mySQL table. It... doesn't, despite echoing that is has.

      Second Page Code:
      <?php
      error_reporting (E_ALL);
      ini_set('displa y_errors', true);
      foreach($HTTP_P OST_VARS as $varname => $value)
      $formVars[$varname]=$value;
      $db1=mysql_conn ect("XXXXX","XX XXXXX","XXXXXXX ");
      mysql_select_db ("tracking") ;
      $query="SELECT * FROM job_status WHERE rid = \"".$formVar s["rid"]."\"";
      $result=mysql_q uery($query);
      $row=mysql_fetc h_array($result );
      $formVars = array();
      $formVars["bone"]=$row["bone"];
      $formVars["ctwo"]=$row["ctwo"];
      $formVars["lthree"]=$row["three"];
      $formVars["rfour"]=$row["rfour"];
      $formVars["ifive"]=$row["ifive"];
      $formVars["fsix"]=$row["fsixl"];
      $formVars["rid"]=$row["rid"];
      mysql_close($db 1);
      ?>
      <html>
      <head>
      <title>Job Status Update</title>
      </head>
      <body bgcolor="white" >
      <form method="post" action="page3.p hp">
      <table>
      <col span="1" align="right">
      <tr>
      <td><font color="blue">Bo ne:</font></td>
      <td><input type="text" name="bone"
      value="<? echo $formVars["bone"]; ?>" size=100></td>
      </tr>
      <tr>
      <td><font color="blue">Ct wo:</font></td>
      <td><input type="text" name="ctwo"
      value="<? echo $formVars["ctwo"]; ?>" size=100></td>
      </tr>
      <tr>
      <td><font color="blue">Lt hree:</font></td>
      <td><input type="text" name="lthree"
      value="<? echo $formVars["lthree"]; ?>" size=100></td>
      </tr>
      <tr>
      <td><font color="blue">Rf our:</font></td>
      <td><input type="text" name="rfour"
      value="<? echo $formVars["rfour"]; ?>" size=100></td>
      </tr>
      <tr>
      <td><font color="blue">If ive:</font></td>
      <td><input type="text" name="ifive"
      value="<? echo $formVars["ifive"]; ?>" size=100></td>
      </tr>
      <tr>
      <td><font color="blue">Fs ix:</font></td>
      <td><input type="text" name="fsix"
      value="<? echo $formVars["fsix"]; ?>" size=100></td>
      </tr>
      <tr>
      <td><font color="blue">ri d:</font></td>
      <td><input type="text" name="rid"
      value="<? echo $formVars["rid"]; ?>" size=100></td>
      </tr>
      <tr>
      </tr>
      <tr>
      <td><input type="submit" value="Submit"> </td>
      </tr>
      </body>
      </html>

      Third Page Code:
      <html>
      <head>
      <title>Job Status Updated</title>
      </head>
      <body bgcolor="white" >
      <?php
      foreach($HTTP_P OST_VARS as $varname => $value)
      $formVars[$varname]=$value;
      $db1=mysql_conn ect("XXXXXX","X XXXXX","XXXXXX" );
      mysql_select_db ("tracking") ;
      echo "Record updated<br><a href=\"tracking .php\">click here</a> to update another record<br>";
      $query="UPDATE job_status set ".
      "bone= \"".$formVar s["bone"]."\",".
      "ctwo= \"".$formVar s["ctwo"]."\",".
      "lthree= \"".$formVar s["lthree"]."\",".
      "rfour= \"".$formVar s["rfour"]."\",".
      "ifive= \"".$formVar s["ifive"]."\",".
      "fsix= \"".$formVar s["fsix"]."\",".
      "\" WHERE rid = \"".$formVar s["rid"]."\"" or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');
      mysql_query($qu ery);
      mysql_close($db 1);
      ?>
      </body>
      </html>

      (I've removed the mysql_connect values from the code. I don't think the first page's code needs to be included as everything is passed perfectly fine from the first to the second and everything works fine on that page)

      Can anyone provide any pointers on what I'm messing up? I'm new to PHP and I feel like I've made some dumb typo but just can't see it. (The table will update in PHPadmin perfectly fine)
      Just the other day I had an update statement that was acting goofy and for the life of me couldn't figure out what was going on. I also use a foreach loop to go through each of the form fields since my form is a dynamic table with multiple rows. Anyways, it ended up being something small, but the way I finally figured out the problem was by printing my update statement to the screen and then the problem was very obvious.

      Also, you said that it is telling you that it is telling you that it is updating, but it looks like you are printing your "Record Updated" before it even does the query. You should be doing an if statement on if the query executed correctly and then printing your message based on that, just a suggestion.

      Comment

      • stantron
        New Member
        • Jan 2008
        • 5

        #4
        Originally posted by brettl
        I don't think you need the foreach($HTTP_P OST_VARS as $varname => $value).

        Read here about Predefined Variables .
        Brett,

        I read that bit about the change from $HTTP_POST_VARS to using $_POST. I have register_global s set to on and am using PHP 4.3. I understand that w/ register_global s on then $HTTP_POST_VARS should behave the same as it is would treated as a global variable. I can't seem to get it to work out yet.

        I did just see something about setting the "name=" portions of my form inputs to (all the same) "name []" and using $_POST in the foreach loop. I'll give that a whirl.

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          Hi.

          $HTTP_POST_VARS and $_POST are essentially the same thing, except the former is an older version that should be avoided.
          If you are using PHP 4 or higher you should use $_POST.

          The "register_globa ls" directive has nothing to do with either the $_POST or the old $HTTP_POST_VARS arrays.
          It simply takes every single POST variable and creates a normal variable in the global scope using the name in the "name" parameter of the input box.

          That is, when "register_globa ls" is on, this code:
          [code=php]
          <?php
          echo $_POST['var1'];
          echo $_POST['var2'];
          ?>
          [/code]
          Could be written like so:
          [code=php]
          <?php
          echo $var1;
          echo $var2;
          ?>
          [/code]
          I don't recommend relying on this because of the security risk it poses. Many hosting services have this turned off so any code relying on this would be useless on such a server.

          As to posting input boxes with "name[]" as a name, that creates an array inside the $_POST array. Like, for example:
          [code=html]
          <form action="page.ph p" method="POST">
          <input type="text" name="textbox[]" />
          <input type="text" name="textbox[]" />
          <input type="text" name="textbox[]" />
          </form>
          [/code]
          Submitting this code would populate the $_POST super-global somewhat like this:
          Code:
          array(
            textbox = array(
              0 => "text in box 1",
              1 => "text in box 2",
              2 => "text in box 3"
            )
          )
          Which could be read like this:
          [code=php]
          foreach($_POST['textbox'] as $_k => $_v) {
          echo "Box #{$_k} = {$_v} <br />";
          }
          [/code]
          Which would print the three values in the textboxes.

          Comment

          • stantron
            New Member
            • Jan 2008
            • 5

            #6
            Atli,

            Thank you for your response. You've pushed me along in my PHP learning experience. On my second page I was able to substitute $_POST for $HTTP_POST_VARS perfectly fine -- the query still successfully pulls the record's fields and inserts them into the html form for editing. However, on the third page (the PHP page updating the mysql table) is still unsuccessful.

            I understand that the foreach() loop is looking for an array. Upon replacing $HTTP_POST_VARS w/ $_POST the script does not run. From your explanation $_POST on my third page contains an array of the name= & value= from the input fields passed from the HTML form from the second page. I've also tried playing around with variations of something like this with no luck:

            [code=php]
            $postArray=$_PO ST ['bone'], ['ctwo'], ['lthree'];
            foreach($postAr ray as $varname => $value)
            $formVars[$varname]=$value;
            [/code]
            ............... and
            [code=php]
            $postArray=$_PO ST [' '];
            foreach($postAr ray as $varname => $value)
            $formVars[$varname]=$value;
            [/code]
            ............... and
            [code=php]
            $postArray=$_PO ST;
            foreach($postAr ray as $varname => $value)
            $formVars[$varname]=$value;
            $db1=mysql_conn ect("XXXXXX","X XXXXX","XXXXXX" );
            mysql_select_db ("tracking") ;
            echo "Record updated<br><a href=\"tracking .php\">click here</a> to update another record<br>";
            $query="UPDATE job_status set ".
            "bone= \"".$formVar s["bone"]."\",".
            "ctwo= \"".$formVar s["ctwo"]."\",".
            "lthree= \"".$formVar s["lthree"]."\",".
            "rfour= \"".$formVar s["rfour"]."\",".
            "ifive= \"".$formVar s["ifive"]."\",".
            "fsix= \"".$formVar s["fsix"]."\",".
            "\" WHERE rid = \"".$formVar s["rid"]."\"" or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');
            mysql_query($qu ery);
            mysql_close($db 1);
            ?>
            [/code]

            I don't understand how to pass the data posted from the form (which I thought would just be contained in $_POST) into the foreach() loop. Depending on how I order things I'll get an error message like "unidentifi ed index at line..." at the lines with "bone= \"".$formVar s["bone"]."\",". etc... I've been reading the PHP Cookbook and thought I had something... but nothing works.

            Every article I come across seems to deal with multiple element forms like checkboxes, radio buttons or drop down fields with and array in the "name=" like you mentioned before. I'm looking for something for several text inputs each with a different "name=".

            Any ideas on what/where I should investigate next?
            Last edited by Atli; Jan 27 '08, 09:07 PM. Reason: Added [code] tags.

            Comment

            • stepterr
              New Member
              • Nov 2007
              • 157

              #7
              Ok, looking at your code for your second page it doesn't look like you are doing anything with arrays in your form. So why don't you just have your update statement like this and not use a for loop, since you don't need it, unless I'm completely overlooking something.

              [PHP]$query="UPDATE job_status set ".
              "bone= \"".$_POST["bone"]."\",".
              "ctwo= \"".$_POST["ctwo"]."\",".
              "lthree= \"".$_POST["lthree"]."\",".
              "rfour= \"".$_POST["rfour"]."\",".
              "ifive= \"".$_POST["ifive"]."\",".
              "fsix= \"".$_POST["fsix"]."\",".
              "\" WHERE rid = \"".$_POST["rid"]."\"" or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');[/PHP]

              Comment

              • Atli
                Recognized Expert Expert
                • Nov 2006
                • 5062

                #8
                After looking more closely at your code, there are a few things on page 3 you should take a closer look at.

                First, you use double-quote marks in your query, where you should be using single-quote marks. MySQL does not use double-quote marks.

                Second, the die() function that would tell you if your query fails is in the wrong place. It should be placed behind the mysql_query() function, not where you define your query string.

                It should look more like this:
                [code=php]
                $query="
                UPDATE job_status SET
                bone = '{$_POST['bone']}',
                ctwo = '{$_POST['ctwo']}',
                lthree = '{$_POST['lthree']}',
                rfour = '{$_POST['rfour']}',
                ifive = '{$_POST['ifive']}',
                fsix = '{$_POST['fsix']}'
                WHERE rid = {$_POST['rid']}";
                $result = mysql_query($qu ery, $db1) or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');
                [/code]
                Notice that you don't have to close the string at every new line. PHP will continue to parse the string until it reaches the closing quote-mark, even if it is not in the same line as the opening quote-mark.

                Also, you do not have to close strings defined in double-quote marks to add variables. PHP will search the string for variables and replace them with their values.
                Array elements can also be added directly into a double-quoted string, like I do in the example above, if they are enclosed in brackets.
                As a rule, I always enclose all variables I place in strings inside brackets so they can be spotted more easily.

                Comment

                • stantron
                  New Member
                  • Jan 2008
                  • 5

                  #9
                  Originally posted by stepterr
                  Ok, looking at your code for your second page it doesn't look like you are doing anything with arrays in your form. So why don't you just have your update statement like this and not use a for loop, since you don't need it, unless I'm completely overlooking something.

                  [PHP]$query="UPDATE job_status set ".
                  "bone= \"".$_POST["bone"]."\",".
                  "ctwo= \"".$_POST["ctwo"]."\",".
                  "lthree= \"".$_POST["lthree"]."\",".
                  "rfour= \"".$_POST["rfour"]."\",".
                  "ifive= \"".$_POST["ifive"]."\",".
                  "fsix= \"".$_POST["fsix"]."\",".
                  "\" WHERE rid = \"".$_POST["rid"]."\"" or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');[/PHP]
                  No, I'm not doing anything with arrays in my form... but the info from each input from the form is put into an array in $_POST; if i understand Atli correctly. That $_POST array of data was then to be sent through the foreach() loop which would parse the info into the appropriate places in the UPDATE query. At least that's how I thought it should work -- but doesn't. I've tried the method you have suggested and it unfortunately does not work either. Thanks for the suggestion though! :)

                  Comment

                  • stepterr
                    New Member
                    • Nov 2007
                    • 157

                    #10
                    Originally posted by stantron
                    No, I'm not doing anything with arrays in my form... but the info from each input from the form is put into an array in $_POST; if i understand Atli correctly. That $_POST array of data was then to be sent through the foreach() loop which would parse the info into the appropriate places in the UPDATE query. At least that's how I thought it should work -- but doesn't. I've tried the method you have suggested and it unfortunately does not work either. Thanks for the suggestion though! :)

                    Strantron, no, for what you are doing you won't need the foreach loop. I think the reason why it didn't work has more to do with your syntax, which I didn't correct when I looked through it the first time, sorry about that. Try this one.

                    [PHP]$query="UPDATE job_status set bone= '".$_POST['bone']."', ctwo= '".$_POST['ctwo']."', lthree= '".$_POST['lthree']."', rfour= '".$_POST['rfour']."', ifive= '".$_POST['ifive']."', fsix= '".$_POST['fsix']."' WHERE rid = '".$_POST['rid']."'"
                    $result = mysql_query($qu ery, $db1) or die('<hr />MySQL Error: ' .mysql_error(). '<hr />');[/PHP]

                    Comment

                    • stantron
                      New Member
                      • Jan 2008
                      • 5

                      #11
                      Earlier today I was reading through some other examples and I figured it out. I found a much simpler way than the other example I was trying to learn from. It was something more like the way Stepterr was recommending. I actually ended up making a few changes to all three of the pages I was referencing initially. Atli, thank you for the assistance in the syntax of things.

                      Thanks to everyone for all of the assistance with my new adventure in mySQL and PHP!

                      Comment

                      • stepterr
                        New Member
                        • Nov 2007
                        • 157

                        #12
                        Originally posted by stantron
                        Earlier today I was reading through some other examples and I figured it out. I found a much simpler way than the other example I was trying to learn from. It was something more like the way Stepterr was recommending. I actually ended up making a few changes to all three of the pages I was referencing initially. Atli, thank you for the assistance in the syntax of things.

                        Thanks to everyone for all of the assistance with my new adventure in mySQL and PHP!
                        Congrats! Glad you were able to get it working.

                        Comment

                        Working...