?
Solved

php form not posting properly

Posted on 2011-09-11
11
Medium Priority
?
312 Views
Last Modified: 2012-05-12
The code below is the "edit" page - it should update the database then return to the "list" page --- BUT it is returning "index.php?pg=editnews&id=49" (instead of "index.php?pg=listnews"

I am using a javascript to redirect after the database is updated. IS THERE AN EASIER WAY? Or can you just correct the problem as described above?

- - - - - - - - - - - -
<?php
/*
 EDIT.PHP
 Allows user to edit specific entry in database
*/
// ----------------------------------------
// ********** FUNCTION renderForm S T A R T
// ----------------------------------------
function renderForm($id, $mod_id, $active, $order_id, $date_m, $date_d, $date_y, $cat01, $cat02, $txt01, $txt02, $img01, $img02, $error){

      // if there are any errors, display them
       if ($error != ''){
             echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
       }
?>
 
      <form action="" method="post">
      <input type="hidden" name="id" value="<?php echo $id; ?>"/>
    <input type="hidden" name="date_post" value="<?php echo date("Y-m-d"); ?>">
    <input type="hidden" name="mod_id" value="news">
            <table width="100%" border="0" cellpadding="0" cellspacing="0">
                     <tr>
                        <td>
                <p style="font-size:1em;padding-left:7px;color:#57996b">News and Announcements Page : EDIT</p></td>
                    <td align="right" style="padding-right:7px">
              <input name="submit" value="Update Now" type="submit" style="font-size:12px;font-weight:bold;text-align:center;margin:-12px -8px 0 0;padding:5px;color:#ffffff;background-color:#ff9900;border:1px solid #000000;display:block;width:150px"></td>
                </tr>
            </table>
        <table width="100%" border="0" cellpadding="2" cellspacing="1" align="center">
                 <tr>
                  <td align="right">Show:</td>
                    <td colspan="3">
                      <select name="active" class="admin_75">
                                    <option value="<?php echo $active; ?>"><?php echo $active; ?></option>
                            <option value="Yes">Yes</option>
                                    <option value="No">No</option>
                              </select>
                    *Order: <input type="text" name="order_id" value="<?php echo $order_id; ?>" class="admin_75" />
                     </td>
                </tr>
                <tr>
                        <td align="right" valign="top">Headline:</td>
                    <td colspan="3">
                         <input type="text" name="txt01" value="<?php echo $txt01; ?>" class="admin_90percent" />
                    </td>
                </tr>
                <tr>
                        <td align="right" valign="top">Body:</td>
                    <td colspan="3">
                       <textarea name="txt02" rows="10" value="<?php echo htmlspecialchars($txt02); ?>" class="admin_90percent"><?php echo $txt02; ?></textarea>
                     </td>
                </tr>
                <tr>
                        <td width="100" align="right" valign="top">Photo:</td>
                    <td>
<?php
echo "<select name='img' class='admin_250'>";
if($img01==''){
      echo '<option value="">none</option>'; };
      echo "<option value='".$img01."'>".$img01."</option>";
      echo "<option value='none'>--> none</option>";
$dirFiles = array();
// opens images folder
if ($handle = opendir('upload_assets/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails" && strpos($file, '.gif')>0 || strpos($file, '.jpg')>0 || strpos($file, '.png')>0) {
                $dirFiles[] = $file;
        }
    }
    closedir($handle);
}
sort($dirFiles);
foreach($dirFiles as $file)
{
    echo "<option value='".$file."'>".$file."</option>";
      // echo $file.'<br />';
}
      echo "</select>";

?> Photo Align:
                      <select name="img02" class="admin_150" >
                              <?php if($img02==''){ echo '<option value="">n/a</option>'; };?>
                    <option value="<?php echo $img02; ?>"><?php echo $img02; ?></option>
                           <option value="Right">Right</option>
                              <option value="Left">Left</option>
                      <option value="Top">Top</option>
                      <option value="Bottom">Bottom</option>
                        </select>
                </td>
          </tr>
        <tr>
              <td align="right">Date:</td>
            <td> <select name="date_m" class="admin_75" >
                        <option value="<?php echo $date_m; ?>"><?php echo $date_m; ?></option>
                      <option value="Jan">Jan</option>
                              <option value="Feb">Feb</option>
                    <option value="Mar">Mar</option>
                    <option value="Apr">Apr</option>
                    <option value="May">May</option>
                    <option value="Jun">Jun</option>
                    <option value="Jul">Jul</option>
                    <option value="Aug">Aug</option>
                    <option value="Sep">Sep</option>
                    <option value="Oct">Oct</option>
                    <option value="Nov">Nov</option>
                    <option value="Dec">Dec</option>
                        </select>
                <select name="date_d" class="admin_55" >
                      <option value="<?php echo $date_d; ?>"><?php echo $date_d; ?></option>
                      <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
                    <option value="10">10</option>
                    <option value="11">11</option>
                    <option value="12">12</option>
                    <option value="13">13</option>
                    <option value="14">14</option>
                    <option value="15">15</option>
                    <option value="16">16</option>
                    <option value="17">17</option>
                    <option value="18">18</option>
                    <option value="19">19</option>
                    <option value="20">20</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>      
                        </select>
                <select name="date_y" class="admin_75" >
                      <option value="<?php echo $date_y; ?>"><?php echo $date_y; ?></option>
                      <option value="2011">2011</option>
                      <option value="2012">2012</option>
                      <option value="2013">2013</option>
                      <option value="2014">2014</option>
                      <option value="2015">2015</option>
                      <option value="2016">2016</option>
                      <option value="2017">2017</option>
                      <option value="2018">2018</option>
                      <option value="2019">2019</option>
                        </select>
                </td>
            </tr>
        <tr>
                  <td colspan="2">&nbsp;</td>
        <tr>
               </table>
</form>  
<?php
 }
// ----------------------------------------
// ********** FUNCTION renderForm END
// ----------------------------------------


// ********** Connection Script and Test
// -----------------------------------------------------
            include("../inc/config.php");                                     // Config script - makes connection
// -----------------------------------------------------
 
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit'])) {             // confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])) {
      // get form data, making sure it is valid
       $id = $_POST['id'];
       $mod_id = mysql_real_escape_string(htmlspecialchars($_POST['mod_id']));
       $active = mysql_real_escape_string(htmlspecialchars($_POST['active']));
       $order_id = mysql_real_escape_string(htmlspecialchars($_POST['order_id']));
       $date_m = mysql_real_escape_string(htmlspecialchars($_POST['date_m']));
      $date_d = mysql_real_escape_string(htmlspecialchars($_POST['date_d']));
      $date_y = mysql_real_escape_string(htmlspecialchars($_POST['date_y']));
      $cat01 = mysql_real_escape_string(htmlspecialchars($_POST['cat01']));
       $cat02 = mysql_real_escape_string(htmlspecialchars($_POST['cat02']));
       $txt01 = mysql_real_escape_string(htmlspecialchars($_POST['txt01']));
       $txt02 = mysql_real_escape_string(htmlspecialchars($_POST['txt02']));
       $img01 = mysql_real_escape_string(htmlspecialchars($_POST['img01']));
       $img02 = mysql_real_escape_string(htmlspecialchars($_POST['img02']));
 
      // check that these fields are both filled in
if ($active == '' || $order_id == ''){
      // generate error message
       $error = 'ERROR: Please fill in all required fields!';
 
      //error, display form
       renderForm($id, $mod_id, $active, $order_id, $date_m, $date_d, $date_y, $cat01, $cat02, $txt01, $txt02, $img01, $img02, $error);
} else {
      // save the data to the database
mysql_query("UPDATE master SET mod_id='$mod_id', active='$active', order_id='$order_id', date_m='$date_m', date_d='$date_d', date_y='$date_y', cat01='$cat01', cat02='$cat02', txt01='$txt01', txt02='$txt02', img01='$img01', img02='$img02' WHERE id='$id'") or die(mysql_error());
 
      // once saved, redirect back to the view page
      echo '<script language="JavaScript" type="text/javascript">';
      echo 'self.location="index.php?pg=listnews';
      echo '</script>';
 }
 } else {
 // if the 'id' isn't valid, display an error
 echo 'Error!';
 }
 } else { // if the form hasn't been submitted, get the data from the db and display the form
 
 // get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
 if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0){
       // query db
       $id = $_GET['id'];
       $result = mysql_query("SELECT * FROM master WHERE id=$id")
             or die(mysql_error());
       $row = mysql_fetch_array($result);
 
 // check that the 'id' matches up with a row in the databse
 if($row){
       // get data from db
      $mod_id = $row['mod_id'];
      $active = $row['active'];
      $order_id = $row['order_id'];
      $date_m = $row['date_m'];
      $date_d = $row['date_d'];
      $date_y = $row['date_y'];
      $cat01 = $row['cat01'];
      $cat02 = $row['cat02'];
      $txt01 = $row['txt01'];
      $txt02 = $row['txt02'];
      $img01 = $row['img01'];
      $img02 = $row['img02'];
 
       // show form
      renderForm($id, $mod_id, $active, $order_id, $date_m, $date_d, $date_y, $cat01, $cat02, $txt01, $txt02, $img01, $img02, '');
 } else {      // if no match, display result      
      echo "No results!";
       }
 } else {       // if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
       echo 'Error!';
       }
 }
?>
0
Comment
Question by:msvarts
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +1
11 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36518301
the form you create in function renderForm has no action so it doesn't redirect the user to the desired page but to the same, where edit function is called. If you have to redirect the user to two different pages accordingly to some if statement, you could add another variable to the function, something like $action and pass the path of the page you want redirect user to.

cheers
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 36518683
Please use the code snippet when you post code at EE.  It makes it easier to read, and it gives us line numbers to facilitate conversation.

Have you considered taking a class in programming fundamentals?  I think you would find it very helpful.  Some things here, like mixing PHP and HTML inside a function are sure recipes for confusion.  If you just line up the control structures it will go a long way toward making your programming easier to read, understand and debug.  A quick count tells me there are perhaps as many as 69 lines of code devoted to getting the date from the client, through the form, and into the data base.  And some of the data base constructs look "unusual" to say the least.  Example:

      $date_m = $row['date_m'];
      $date_d = $row['date_d'];
      $date_y = $row['date_y'];

It appears that you may have the date in three pieces in three separate columns of the data base.  If that's the case, you might want to redesign the DATETIME handling along the lines suggested by this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

As far as using JavaScript to redirect after the action script runs a query, that is not a technically competent design, for a variety of reasons.  When the form script is run and the form is submitted, the action script is started, and since there is no action attribute in the form tag, it is the same URL as the form script.  Once the action script has finished its work, presumably to update a data base record, you can use the PHP header() function if you want to redirect.  Just throwing the JavaScript into the browser output stream probably will not work because there will be no event to start the JavaScript.  If it were my project, I would avoid the redirect completely and just load the response script directly into the action script.  You can use require_once() to accomplish something like that.

The relationship between the form script, the action script, and the confirmation script are shown in the code snippet.  As you add more form fields and data base updates, it looks more complicated.  But the design pattern remains the same.

HTH, ~Ray
<?php // RAY_post_example.php
error_reporting(E_ALL);
echo "<pre>"; // MAKE IT EASY TO READ



// THIS ILLUSTRATES THE RELATIONSHIP BETWEEN THE 'ACTION' AND THE 'FORM' WHEN COMBINED INTO A SINGLE PHP SCRIPT FILE



// SET A DEFAULT VALUES FOR A VARIABLE TO PREPOPULATE THE FORM - THIS COULD COME FROM A DATA BASE, OR MIGHT BE EMPTY
$my_INPUT_Field = 'ORIGINAL DATA';



// HAS ANYTHING BEEN POSTED? IF SO, $_POST IS SET AND CONTAINS THE DATA
if (!empty($_POST))
{


    // THIS IS THE ACTION SCRIPT - SHOW THE POST ARRAY, UPDATE A DATA BASE, ETC.
    var_dump($_POST);



    // THIS IS THE CONFIRMATION SCRIPT AT THE END OF THE ACTION SCRIPT
    echo 'ACTION COMPLETED';
    die();
    
    
}



// THIS IS THE FORM SCRIPT CREATED IN HEREDOC NOTATION
$form = <<<ENDFORM
<form method="post">
TYPE SOMETHING HERE:
<input type="text"   name="my_INPUT_Field"   value="$my_INPUT_Field" />
<input type="hidden" name="my_HIDDEN_Field"  value="Not Really Much of a Secret" />
<input type="submit" name="my_SUBMIT_Button" value="go" />
</form>
ENDFORM;

// WRITE THE FORM TO THE BROWSER
echo $form;

Open in new window

0
 

Author Comment

by:msvarts
ID: 36535780
I've requested that this question be deleted for the following reason:

Too confusing for a newbie
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36535781
I don't really think that my post ID:36518301 is too confused, Anyway, if something is too confused/ing simply ask for some explanation and we'll be happy to givi it.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36535888
Agree with marqusG, 100%

This book will help you get some of the foundation you need to understand PHP and MySQL.
http://www.sitepoint.com/books/phpmysql4/

And this little article will explain why you should not be too impatient with yourself as you are trying to learn these technologies.
http://norvig.com/21-days.html

It's just plain hard work.  I don't do programming because it is easy.  I do programming because it is hard, complicated and has high barriers to entry.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36553232
I recommend to close this question accepting Ray's comment http:#36518683. Perhaps it not be exactly what asker want but it points him in the good direction.

Cheers
marqusG
0
 

Expert Comment

by:South Mod
ID: 36597708
All,
 
Following an 'Objection' by marqusG (at http://www.experts-exchange.com/Q_27307358.html) to the intended closure of this question, it has been reviewed by at least one Moderator and is being closed as recommended by the Expert.
 
At this point I am going to re-start the auto-close procedure.
 
Thank you,
 
SouthMod
Community Support Moderator
0
 

Author Comment

by:msvarts
ID: 36591252
I can certainly accept Rays comments as a solution. But I do want to add a few comments. I, like many come here as newbies trying to learn - and when someone's suggest you take a class, it defeats the purpose of me being a paid member of EE. I do totally agree with your comments but as a user, please understand that it is an art to communicate what "you know" to newbies who do not know much of what you might reference. I can tell you that as a newbie, examples are or little value unless they are "working" examples that function and can then be deciphered by those trying to learn. Hypothetical code does little to teach and using "example dat" and "original data" doesn't work for many beginners. Do not misunderstand me, I GREATLY APPRECIATE ALL OF YOUR EXPERTISE and love the help I have gathered here - but I have run into condescending advice on more than one occasion... But again thanks - I will keep plugging along and grow thicker skin as the advice is beneficial...
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36591340
Hi, msvarts. I have to add some notes also :-)

First, I have to repeat that my first comment ID:36518301 was not confused at all: I only highlighted that your form had no action, so it is difficult it does something.

Second, and more important, what here at EE is nopt so mutch appreciated is that askers do a question and then refuse to interact with us. I try to explain better: if we use terms too technical, confused or vague explanations, if we say something which seems to not make sense, well, ask for more explanation, tell us what you don't understand and we'll try to be more clear.

We all have been newbies, butthere are different level of knowledge for newbies also. Otherwise, learning something is a trial and error process and overall is a process that requires a deep interaction between learner and techer, questions and answers, since each answer virtually takes to new questions.

In this case, on the contrary, you have only done a question and then close the question without talk with us: this way it is only a question of luck to find a good answer for your questions ;-)

Cheers
0

Featured Post

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question