PHP: get the value of TEXTBOX then pass it to a VA

2020-05-27 08:22发布

问题:

My Problem is:

I want to get the value of textbox1 then transfer it to another page where the value of textbox1 will be appeared in the textbox2.

Below is my codes for PHP:

<html>
<body>

<form name='form' method='post' action="testing2.php">

Name: <input type="text" name="name" id="name" ><br/>

<input type="submit" name="submit" value="Submit">  

</form>
</body>
</html>

I also add the code below and the error is "Notice: Undefined index: name"

<?php 
$name = $_GET['name'];
echo $name;
?>

or

<?php 
$name = $_POST['name'];
echo $name;
?>

回答1:

In testing2.php use the following code to get the name:

if ( ! empty($_POST['name'])){
    $name = $_POST['name']);
}

When you create the next page, use the value of $name to prefill the form field:

Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"><br/>

However, before doing that, be sure to use regular expressions to verify that the $name only contains valid characters, such as:

$pattern =  '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
if (preg_match($pattern, $name) == 1){
    //continue
} else {
    //reload form with error message
}


回答2:

I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.

if((isset($_POST['name'])) && !empty($_POST['name']))
{
    $name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
    echo $name;
}


回答3:

You are posting the data, so it should be $_POST. But 'name' is not the best name to use.

name = "name"

will only cause confusion IMO.



回答4:

Inside testing2.php you should print the $_POST array which contains all the data from the post. Also, $_POST['name'] should be available. For more info check $_POST on php.net.