Jump to content

Update saves blank data when using Redirect


Kathy_OC

Recommended Posts

I am trying to update a record in a MySQL database and then redirect to another page. I can create the record, but can't seem to figure out how to update it and redirect to the next page.  The problem seems to be when I use both the update and the redirect. The update works fine if I don't redirect.  When I update and then redirect, the fields are saved with blank data (but the date/time stamp shows the current time so an update is occurring).  Sections of code that I have tried are below.

 

// The page redirects and the DateSubmitted field is updated, but the technology and description fields are blank

$query = "UPDATE request SET Technology='$Technology', Description='$Description', DateSubmitted=now() WHERE RequestID = " . $RequestID;

mysql_query($query);

header('Location: http://example.com/php/CostInfo.php');

exit();

 

// This updates all three fields with data, but doesn't redirect to the next page (since I purposely left out the header function for testing)

$query = "UPDATE request SET Technology='$Technology', Description='$Description', DateSubmitted=now() WHERE RequestID = " . $RequestID;

mysql_query($query);

 

// This works but creates a new record (of course)

$query = "INSERT INTO request (Technology, Description, DateSubmitted) VALUES ('$Technology','$Description', now())";

mysql_query($query);

header('Location: http://example.com/php/CostInfo.php');

exit();

 

What I'm trying to do is:

the user enters data to update a record that already exists

the user clicks on the submit button

the database is updated

the next screen is displayed

 

I'm a newbie and feel like I must be missing something obvious, but what? I would appreciate any help or advice about how to go about making this work.

 

Thanks,

Kathy

 

Link to comment
Share on other sites

I set the variables above the code that I included.  Here's what it looks like:

 

$Technology = htmlspecialchars($_POST['txtTechnology']);

$Description = htmlspecialchars($_POST['txtDescription']);

echo "<br>" . $Technology . "<br>";

echo $Description . "<br>";

 

When I echo the fields to the screen, they show the correct data.

 

Kathy

 

Link to comment
Share on other sites

try:

 

$query = "UPDATE `request` SET `Technology`='".mysql_escape_string($_POST['txtTechnology'])."', `Description`='".mysql_escape_string($_POST['txtDescription'])."', DateSubmitted=now() WHERE `RequestID` = '" . $RequestID."'";
mysql_query($query);
header('Location: http://example.com/php/CostInfo.php');
exit();

 

added backticks, used the _POST cariables instead, and used mysql_escape_string to prevent sql injection.

 

 

hope this helps,

Link to comment
Share on other sites

Thanks, but unfortunately that didn't help. 

 

The update works fine unless I include the redirect.  When I include the redirect then the update saves blanks (not nulls) in the text fields.

 

Even if I redirect using

<meta HTTP-EQUIV="REFRESH" content="0; url=<?php echo"CostInfo.php";?>"> 

instead of the header command, it behaves the same way.

 

I am really baffled by this.  Since I'm new to PHP, I'm wondering ... Should I be trying a completely different approach?

 

Kathy

Link to comment
Share on other sites

This is probably more than you want/need, but here's the code.

 

I am submitting the form, updating the fields (or trying to), and then redirecting the page.  This is the second screen of a multi-page form.  The user enters some basic info on a different screen so the record has already been created - the first screen uses the same basic logic as this second screen except the first screen has an insert and redirect.  The first screen works great - it's this update screen which is causing me problems.

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?php
error_reporting(E_ALL); 
session_start(); 
?>
<html>
<!-- #BeginTemplate "/Templates/IntranetTemplate.dwt" --><!-- DW6 -->
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="robots" content="noindex, nofollow">

<!-- #BeginEditable "page_title" -->
<title>Technology Requests</title>
<!-- #EndEditable -->

<link href="/css/intranetstyle.css" media="all" rel="stylesheet" type="text/css">
<link href="/css/header.css" rel="stylesheet" type="text/css">
<script src="/css/intranet_include_template.js" type="text/javascript"></script>
<link href="/css/intranetprint.css" media="print" rel="stylesheet" type="text/css">
</head>

<body>

<div class="HeaderText"> 
<!-- #BeginEditable "dept_header" -->
<?php
include("header.htm");
?>
<!-- #EndEditable --> 

  <!-- end of top navigation -->
<div class="MainText">
  
<script src="/css/netscape4.js" type="text/javascript"></script> 

  <!-- #BeginEditable "page_content" -->
<?php
require_once("dataconn.php");

if(isset($_SESSION['varRequestID']))
{
$RequestID = $_SESSION['varRequestID'];
echo "RequestID is: " . $RequestID;
} else {
echo "<h2>ERROR: Request number has not been found.</h2>";
echo "<h2><a href='index.php'>Return to Home Page</a></h2>";
// should not display the form
exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // The request is a POST, so validate the form
echo "<br><b>form has been submitted - " . $_SERVER['SCRIPT_NAME'] . "</b><br>";
    $errors = validate_form();
    if (count($errors)) {
        // If there were errors, redisplay the form with the errors
        display_form($errors);
    } else {
        // The form data was valid, so save data to database and 
	// display next data entry screen

	// update record in database
	//$Technology = htmlspecialchars($_POST['txtTechnology']);
	//$Description = htmlspecialchars($_POST['txtDescription']);

	$Technology = mysql_real_escape_string($_POST['txtTechnology']);
	$Description = mysql_real_escape_string($_POST['txtDescription']);
	echo "<br>" . $Technology . "<br>";
	echo $Description . "<br>";

	//$query = "UPDATE request SET Technology='".$Technology."', Description='".$Description."', DateSubmitted=now() WHERE RequestID = ".$RequestID; 
	$query = "UPDATE `request` SET `Technology`='".mysql_escape_string($_POST['txtTechnology'])."', `Description`='".mysql_escape_string($_POST['txtDescription'])."', DateSubmitted=now() WHERE `RequestID` = '" . $RequestID."'";

	echo "query: " . $query . "<br>";
	$result = mysql_query($query);
	echo "result: " . $result . "<br>";

	//if($result){
	if($result && mysql_affected_rows()){
		echo "Should have worked";
		//echo "<meta HTTP-EQUIV='REFRESH' content='0; url=CostInfo.php'>"
		header('Location: http://example.com/php/CostInfo.php');
		exit();
	}else{
		echo "There has been an error." . mysql_error();
	}
}
} else {
// display the form
display_form(array());
}

function display_form($errors) {
   
    // Set up defaults
    $defaults['txtTechnology'] = isset($_POST['txtTechnology']) ? htmlentities($_POST['txtTechnology']) : '';
    $defaults['txtDescription'] = isset($_POST['txtDescription']) ? htmlentities($_POST['txtDescription']) : '';

if (isset($_SESSION['varRequestID']))
{
	$RequestID = $_SESSION['varRequestID'];
	echo "<h2>Request Number: " . $RequestID . "</h2>";
} else {
	echo "session variable has not been set <br>";
}

>

<p>Instructions: The technology and description fields are required. </p>
<form name="frmTechRequested" method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
    <p>
    <label for="txtTechnology">Technology:</label>
      <input name="txtTechnology" type="text" id="txtTechnology" size="60" value='<?php echo $defaults['txtTechnology'] ?>'>
  	<?php print_error('txtTechnology', $errors) ?>
    </p>
    <p>
      <label for="txtDescription">Description:</label>
      <textarea name="txtDescription" cols="60" rows="3" id="txtDescription"><?php echo $defaults['txtDescription'] ?></textarea>
  	<?php print_error('txtDescription', $errors) ?>
    </p>
    <table width="90%">
      <tr>
        <th>Component</th>
        <th>Description</th>
        <th>Cost</th>
        <th>Vendor</th>
      </tr>
  <?php

    $MaxComponents = 10;
	for ($NumComponents = 1; $NumComponents < $MaxComponents + 1; $NumComponents++)
	{
	echo "<tr>\n";
        echo "<td><input name='txtComponent" . $NumComponents . "' type='text' id='txtComponent" . $NumCompenents . "'></td>\n";
        echo "<td><input name='txtDescription" . $NumComponents . "' type='text' id='txtDescription" . $NumCompenents . "'></td>\n";
        echo "<td><input name='txtCost" . $NumComponents . "' type='text' id='txtCost" . $NumCompenents . "'></td>\n";
        echo "<td><input name='txtVendor" . $NumComponents . "' type='text' id='txtVendor" . $NumCompenents . "'></td>\n";
	echo "</tr>\n";
    }

  ?>
   </table>
    <p> </p>
    <p>   
      <input type="submit" name="Submit" value="Next Screen >>" id="Submit">
       
      <input type="reset" name="Cancel" value="  Cancel  " id="Cancel" onClick="document.location='index.php'">
    </p>
    </form>
<p> </p>
  
<?php
}	// end of display_form function

// A helper function to make generating the HTML for an error message easier
function print_error($key, $errors) {
    if (isset($errors[$key])) {
	// ***** SHOULD ADD ERROR CLASS TO CSS *****
	print "   ** {$errors[$key]} **";
    }
}

function validate_form() {
    // Start out with no errors
    $errors = array();
    
    // technology is required
    if (! (isset($_POST['txtTechnology']) && (strlen($_POST['txtTechnology']) > 0))) {
        $errors['txtTechnology'] = 'Please enter a technology';
    }
// description is required
    if (! (isset($_POST['txtDescription']) && (strlen($_POST['txtDescription']) > 0))) {
        $errors['txtDescription'] = 'Please enter a description';
    }

    return $errors;
}

?>

  <!-- #EndEditable --> 

  <!-- #BeginEditable "dept_footer" -->
   <?php
   include("footer.php");
   ?>
  <!-- #EndEditable -->  
  </div>

</div>

<div class="LeftMenu">
<script src="/css/intranetmenu.js" type="text/javascript"></script>
</div>

<div class="LeftMenuBackground">
<p> </p>
</div>

</body>
<!-- #EndTemplate --></html>

 

Thanks for taking a look at this.

Kathy

Link to comment
Share on other sites

Thanks for your replies.

 

The echo variables and query look fine.  I've tried the query with and without mysql_real_escape_string and it doesn't change the behavior.

 

Like I said in my original message, the update query works great if I comment out the redirect.  When the redirect is in my code, the fields are saved as blanks.

 

Kathy

Link to comment
Share on other sites

so the query is definetely fine? ok so this must be some sort of bug in your platform/installation of mysql and php.

 

submit this to the php bugs website i would suggest.

--------------------

 

or try a different version of php/apache/mysql/libmysql.dll

 

--------------------

 

You could Zip up your database and script, let someone else test it on their server to see if it really is your installation/version.

 

 

A solution to your problem would be to put the code that "redirects" into the same folder as the page it is redirecting to. Then just "Include()" the page rather than redirecting, everything should work fine.

 

All you would have to do is put this update function into a stand-alone file and have the html form POST directly to that file, then all you need is to include the redirection :P

Link to comment
Share on other sites

Well, I'm using IIS so I have been wondering if my installation was part of the problem.  I have upgraded to PHP 5.2.5 (from 5.2.3).  I searched the php bug reports and found some that are similar to my problem.  One of the suggestions was to use the IP address in the header function - that works except I lose my session variable on the next page.  So I changed the header function back to using the name, removed my session variable from the script (used a static value instead) and my update and redirect work.  Now I'm thinking that something is happening to the session variable and I'm pursuing that idea.

 

Thanks to everyone for your help.  Maybe it will become clear over the weekend.  :)

 

Kathy

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.