I am new in php, so I need your help. At first I created two .php files. The first included a form and the second included the message.
I wish to replace the form to a message in the same page after submit. how I do that?
<?php
$message="";
if (isset($_POST["submitButton"])) {
$name= $_POST["name"];
$age= $_POST["age"];
$username= $_POST["username"];
$message= "your name is ". $name. ",you are ".$age
." and your reddit's username is ".$username;
}
?>
<html>
<head>
<meta charset="utf-8">
<title>new file</title>
</head>
<body>
<?php echo $message; ?>
<form action="" method="post">
<table >
<tr>
<th>name:</th>
<td>
<input type="text" name="name" >
</td>
</tr>
<tr>
<th>age:</th>
<td>
<input type="text" name="age" >
</td>
</tr>
<tr>
<th>username:</th>
<td>
<input type="text" name="username">
</td>
</tr>
</table>
<input type="submit" value="click here for save" name="submitButton">
</form>
</body>
</html>
Put the form
in a conditional.
<?php
$message= isset($_POST["submitButton"]) ? "your name is ". $_POST["name"]. ",you are ".$_POST["age"]
." and your reddit's username is ".$_POST["username"] : "";
?>
<html>
<head>
<meta charset="utf-8">
<title>new file</title>
</head>
<body>
<?php if (!empty($message)) {
echo $message;
} else { ?>
<form action="" method="post">
<table >
<tr>
<th>name:</th>
<td>
<input type="text" name="name" >
</td>
</tr>
<tr>
<th>age:</th>
<td>
<input type="text" name="age" >
</td>
</tr>
<tr>
<th>username:</th>
<td>
<input type="text" name="username">
</td>
</tr>
</table>
<input type="submit" value="click here for save" name="submitButton">
</form>
<?php } ?>
</body>
</html>
You can make use of below given codes. empty() function Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
By using it in condition it can solve your problem.
<?php
$message="";
if (isset($_POST["submitButton"])) {
$name= $_POST["name"];
$age= $_POST["age"];
$username= $_POST["username"];
$message= "your name is ". $name. ",you are ".$age
." and your reddit's username is ".$username;
}
?>
<html>
<head>
<meta charset="utf-8">
<title>new file</title>
</head>
<body>
<?php
if (!empty($message)) {
echo $message;
}else{
?>
<form action="" method="post">
<table >
<tr>
<th>name:</th>
<td>
<input type="text" name="name" >
</td>
</tr>
<tr>
<th>age:</th>
<td>
<input type="text" name="age" >
</td>
</tr>
<tr>
<th>username:</th>
<td>
<input type="text" name="username">
</td>
</tr>
</table>
<input type="submit" value="click here for save" name="submitButton">
</form>
<?php } ?>
</body>