473,749 Members | 2,432 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Transferring $_GET variable to $_POST

23 New Member
I have a script that recieves an id number via the address bar when a link is clicked.

ie . index.php?id=1 if the link was for the story whose ID is 1.

My script checks if a user is logged in, if not they are redirected to the login page.

If logged in they may edit the story.

I assign $_GET['id'] to $id.

So I check if the form is submitted, if submitted, handle the data, output a success message(for now).

$_GET['id'] is ok up to this point, the correct id is outputted when checked with a simple echo $_GET['id']; and with an echo $id'

If the form has not been submitted then the user will type their data into the input form and then submit it.

The problem is that when the form is submitted the $_GET['id'] is not passed.

Meaning that when the form goes through the If (isset($_POST['submitted'] {
the query SELECT * FROM table WHERE id = $ID fails because there is no id as the $_GET['id'] was never passed on when the form was submitted.

So, I know why the query is failing, ie. $id doesn't get a variable from $_GET['id'] when the form is submitted.

I just don't know who I would pass the ID from $_GET['id'] before the form has been submitted to $_GET['id'] after the page has been submitted.

Any help would be greatly appreciated.

Thankyou in advance.


Here is my code:

Expand|Select|Wrap|Line Numbers
  1. <?php 
  2. # Filename - edit_story.php
  3. # Date - 9th August 2007
  4. # Author - Stephen Hoult
  5. # Author Email - stephen@hoult.org.uk
  6.  
  7. // This file allows logged in users to edit a story.
  8.  
  9. // Include config file for error management and such
  10. include('./includes/config.inc.php');
  11.  
  12. // Set page title and include HTML header
  13. $page_title = 'Edit a Story';
  14. include('./includes/header.html');
  15.  
  16.  
  17. // If no first_name variable exists, redirect the user.
  18. if (!isset($_SESSION['first_name'])) {
  19.  
  20.     // Start defining the URL.
  21.     $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
  22.     // Check for a trailing slash.
  23.     if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
  24.         $url = substr ($url, 0, -1); // Chop off the slash.
  25.     }
  26.  
  27.     // Add the page.
  28.     $url .= '/login.php';
  29.  
  30.     ob_end_clean(); // Delete the buffer.
  31.     header("Location: $url");
  32.     exit(); // Quit the script.
  33.  
  34. } else { // First name variable exists - user is logged in
  35.  
  36.  
  37.         // Connect to the Database
  38.         require_once('../mysql_connect_ur.php');
  39.  
  40.  
  41.     if (isset($_POST['submitted'])) { // if the form has beeen submitted
  42.  
  43.         echo' The form has been submitted.';
  44.  
  45.         // Handle the form
  46.         // Get story ID
  47.             if (isset($_GET['id'])) {
  48.                 $id = escape_data($_GET['id']);
  49.                 echo '<p>The story ID is: ' . $id . '.</p>';
  50.             } else {
  51.                 $id = FALSE;
  52.                 echo '<p><font color="red" size="+1">No ID has been selected.</font></p>';
  53.             }
  54.  
  55.         // Validate title
  56.         if(!empty($_POST['title'])) {
  57.             $t = escape_data($_POST['title']);
  58.         } else {
  59.             echo '<p><font color="red" size="+1">Please enter a title.</font></p>';
  60.         }
  61.  
  62.         // Validate main text
  63.         if(!empty($_POST['main_text'])) {
  64.             $mt = escape_data($_POST['main_text']);
  65.         } else {
  66.             echo '<p><font color="red" size="+1">Please enter the main text.</font></p>';
  67.         }
  68.  
  69.  
  70.                 // Check that the ID exists in the database.
  71.                 // Build query
  72.                 $query = "SELECT id, title, main_text FROM content WHERE id =$id";
  73.                 $result = mysql_query($query);
  74.  
  75.                 echo '<p>Query: ' . $query .'</p>';
  76.  
  77.                     if (mysql_num_rows($result == 1)) { // If a row was found by the query - ie the story id exists in the table.
  78.  
  79.                         echo '<p>Success a row for this ID exists.</p>';
  80.  
  81.  
  82.                     } else {        
  83.                         echo '<p><font color="red" size="+1">The selected ID does not exist in the database. Please try again.</font></p>';
  84.                     } // End mysql_num_rows($result) to see if id exists in the table.
  85.  
  86.  
  87.         } else { // The form has not yet been submitted - Display the form    
  88.         echo' The form hasn\'t been submitted.';
  89.         // Get story ID
  90.             if (isset($_GET['id'])) {
  91.                 $id = escape_data($_GET['id']);
  92.                 echo '<p>The story ID is: ' . $id . '.</p>';
  93.             } else {
  94.                 $id = FALSE;
  95.                 echo '<p><font color="red" size="+1">No ID has been selected.</font></p>';
  96.             }
  97.  
  98. ?>
  99.  
  100.  
  101. <fieldset><legend>Edit a story</legend>
  102.  
  103. <form action="edit_story.php" method="post" >
  104.  
  105.     <p>Title: <input type="text" name="title" size="30" maxlength="50" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
  106.  
  107.     <p>Main Text<textarea name="main_text" cols="40" rows="5"/><?php if (isset($_POST['main_text'])) echo $_POST['main_text']; ?></textarea></p>
  108.  
  109.     <p><input type="submit" name="submit" value="Submit" /></p>
  110.     <input type="hidden" name="submitted" value="TRUE" />    
  111.  
  112.  
  113. </form>
  114.  
  115. </fieldset>
  116.  
  117. <?php
  118. }// End of if is submitted                    
  119.  
  120. } // End of is logged in
  121.  
  122. include('./includes/footer.html'); // Include HTML footer
  123. ?>
  124.  
Aug 10 '07 #1
2 3138
keeps21
23 New Member
I figured out a fix for this.

To solve the problem I created a hidden text box and used it to assign $id to $_POST['id']

Allowing me to pull the id from $_POST['id'] when the form had been submitted.

Here is the fixed script.

[php]
<?php
# Filename - edit_story.php
# Date - 9th August 2007
# Author - Stephen Hoult
# Author Email - stephen@hoult.o rg.uk

// This file allows logged in users to edit a story.

// Include config file for error management and such
include('./includes/config.inc.php' );

// Set page title and include HTML header
$page_title = 'Edit a Story';
include('./includes/header.html');


// If no first_name variable exists, redirect the user.
if (!isset($_SESSI ON['first_name'])) {

// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVE R['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}

// Add the page.
$url .= '/login.php';

ob_end_clean(); // Delete the buffer.
header("Locatio n: $url");
exit(); // Quit the script.

} else { // First name variable exists - user is logged in


// Connect to the Database
require_once('. ./mysql_connect_u r.php');


if (isset($_POST['submitted'])) { // if the form has beeen submitted

echo' The form has been submitted.';

// Get story ID
if (isset($_POST['id'])) {
$id = escape_data($_P OST['id']);
echo '<p>The story ID is: ' . $id . '.</p>';
} else {
$id = FALSE;
echo '<p><font color="red" size="+1">No ID has been selected.</font></p>';
}

// Handle the form

// Validate title
if(!empty($_POS T['title'])) {
$t = escape_data($_P OST['title']);
} else {
echo '<p><font color="red" size="+1">Pleas e enter a title.</font></p>';
}

// Validate main text
if(!empty($_POS T['main_text'])) {
$mt = escape_data($_P OST['main_text']);
} else {
echo '<p><font color="red" size="+1">Pleas e enter the main text.</font></p>';
}


// Check that the ID exists in the database.
// Build query
$query = "SELECT id, title, main_text FROM content WHERE id = $id";
$result = mysql_query($qu ery);
$num = mysql_num_rows( $result);



if ($num == 1) { // If a row was found by the query - ie the story id exists in the table.

echo '<p>Success a row for this ID exists.</p>';

// Update the database
$query = "UPDATE content SET title='$t', main_text='$mt' WHERE id = $id";
$result = mysql_query($qu ery);

echo $query ;

// Check to see if update was successful
if (mysql_affected _rows() == 1) { // If 1 row was affected by the update
echo '<p>The story has been edited.</p>';

} else {
echo '<p><font color="red" size="+1">The story could not be updated. Please try again</font></p>';
}// End If update was successful


} else {
echo '<p><font color="red" size="+1">The selected ID does not exist in the database. Please try again.</font></p>';
} // End mysql_num_rows( ) to see if id exists in the table.


} else { // The form has not yet been submitted - Display the form
echo' The form hasn\'t been submitted.';

// Get story ID
if (isset($_GET['id'])) {
$id = escape_data($_G ET['id']);
echo '<p>The story ID is: ' . $id . '.</p>';
} else {
$id = FALSE;
echo '<p><font color="red" size="+1">No ID has been selected.</font></p>';
}

?>


<fieldset><lege nd>Edit a story</legend>

<form action="edit_st ory.php" method="post" >

<p>Title: <input type="text" name="title" size="30" maxlength="50" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>

<p>Main Text<textarea name="main_text " cols="40" rows="5"/><?php if (isset($_POST['main_text'])) echo $_POST['main_text']; ?></textarea></p>

<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="submitted " value="TRUE" />
<input type="text" name="id" value="<?php $_POST['id'] = $id; echo $_POST['id'] ;?>">


</form>

</fieldset>

<?php
}// End of if is submitted

} // End of is logged in

include('./includes/footer.html'); // Include HTML footer
?>
[/php]
Aug 10 '07 #2
pbmods
5,821 Recognized Expert Expert
Changed thread title to better describe a problem (threads tend to get more responses when the title contains nouns *and* verbs, with emphasis on plural).

Heya, Keeps.

Thanks for posting your solution.

Glad to hear you got it working! Good luck with your project, and if you ever need anything, post back anytime :)
Aug 13 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2659
by: Phil Powell | last post by:
I have an inherited class method that is required to *only* handle items from $_POST (and $_POST alone, for security reasons), for validation and action processing. Problem is that there is a section in my application that has to put everything into an encoded query string for HTML reasons (the page is a giant form and if I were to put the stuff into individual forms, I would have a bunch of embedded forms inside one form and that is an...
4
1948
by: Sjaakie Helderhorst | last post by:
Hi, I recently installed the latest Fedora Core 2 but have some troubles of which I'm not sure are PHP or Apache 2 related... apologies if this is the wrong group. "http://www.domain.ltd/index.php?var=123&" Somehow, $var returns an empty value, while $_GET returns '123'. Need I change a parameter in php.ini or somewhere else? Thanks in advance for any help!
7
11878
by: Dan | last post by:
I was trying to troubleshoot a login page that doesn't work - it keeps saying the login/password is missing - when my tracing discovered this peculiar behavior. register_globals is off, so at the top of my script I assign a few variables to incoming GET and POST values. $login = clean($_POST, 30); $passwd = clean($_POST, 30);
7
1936
by: sketch | last post by:
I have one page that does 3 different things depending on $_GET: 1. It shows an index with items. 2. It shows an item with a form to submit an amount. 3. It confirms the amount. I was just wondering, since I haven't approached anything like this if I'm ding something I shouldn't be doing. To get the post variable to work, I had to add some get variables to the form action. Would it be better to use hidden fields? <?php
1
2167
by: stephane | last post by:
I have a problem which must be in this : print" <script type='text/javascript'> document.location.replace('http://127.0.0.1/add_task.php?req_id={$maxValue}&tk_request_name={$req_name}'); </script>"; or maybe here, in file2 <?php $tk_req_id = $_GET;
1
5679
by: stephane | last post by:
I have a problem which must be in this : print" <script type='text/javascript'> document.location.replace('http://127.0.0.1/add_task.php?req_id={$maxValue}&tk_request_name={$req_name}'); </script>"; or maybe here, in file2 <?php $tk_req_id = $_GET;
2
1775
by: lawrence k | last post by:
I noticed this odd PHP function in an article about AJAX and Prototype: > http://www.sitepoint.com/article/painless-javascript-prototype/2 > > Prototype adds a custom HTTP header to all its AJAX requests so that your server > application can detect that it's an AJAX call, rather than a normal call. The header is: > > X-Requested-With: XMLHttpRequest >
2
1547
by: Dino | last post by:
dear all, i got this script form a customer. in general, it recieves data which is send via http to a server and generates a .xml file from this data. because i'm not familar with .asp, i'm totally lost transferring this script to php. i don't understand which way the data is recieved and how it's saved. as long this ia a very short script, i post it here. it would bne GREAT if
17
1876
by: sheldonlg | last post by:
I need to do some modifications on some code I just inherited and that code has me baffled. On one page, caller.php, with method get there is an anchor with href="foo.php?bar=123". On foo.php, the URL shows the parameter. So far, so good. In foo.php there is no $_GET statement to decipher the value from bar. Furthermore, I did a grep of the entire code base for $_GET and for $_REQUEST and there was none. The code then proceeds to...
0
8833
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9568
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6079
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4709
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3320
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2218
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.