Jump to content

pass variable from one file to another


mazinger

Recommended Posts

I'm trying to learn php from a book and one of the first examples is a simple form where the user enters a name and the name is displayed, all this is made on one file. I want to split it into two files, but can't get it to work. 

 

This is what I have on the first file where the form is. 

<html>
	<head>
		<title>Form Test</title>
	</head>
	<body>
		Your name is <?php echo $name ?> 
		<form method="post" action="formtest.php">
			What is your name
			<input type="text" name="name"/>
			<input type="submit"/>
		</form>
	</body>
</html>

This is the second file I created by taking the php out of the first file.  

<?php

if(isset($_POST['name']))
{
	$name = $_POST['name']; 
}
else
{
	
	$name = "Enter a name"; 
}

require_once('formtest.php');
?>

The variable $name contains whatever the user typed into the form and I want that to be displayed but when I test it I get the following error message

 

Notice: Undefined variable: name in C:\xampp\htdocs\testing\formtest.php on line 7

 

Hopefully you guys can tell me what I'm doing wrong, I know I could do this in one file but I want to see If I can do it in two separate files, thanks in advance for your help

Link to comment
Share on other sites

I guess I should have specified the names of the files. 

The first file on my post is called formtest.php and the second one is called formtest-controller.php  

Are you saying I should reverse the names? 

 

Thanks for helping.  

Link to comment
Share on other sites

You still need the require_once, but remember to change the filename.

 

The first file that executes (second code you posted) has the code for $name. That will be formtest.php. You can then use require_once to include the second file (first code you posted) which has the HTML.

Link to comment
Share on other sites

After all of that I still get the same error, 

 

Notice: Undefined variable: name in C:\xampp\htdocs\testing\formtest.php on line 7

 

I used to get it as soon as the page loaded but now i get it after I enter the name.

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.