Home > Blockchain >  Form data sent via POST method gets empty
Form data sent via POST method gets empty

Time:02-23

I am posting the "user" variable to another page i.e. Survey.php as follows:

index.html

<form action="Survey.php" method="post" name="frm">
  <div><input type="text" name="user"></div>
  <div><input type="submit" value="Start" ></div>
</form>

I can access the "user" variable on Survey.php page on its first load. Now, because I have another form on this page as well, which posts data to itself.

Survey.php

$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$user', '$email');";
echo $sql;
}
<form action="survey.php" method="post">
  <div><input type="text" name="email"></div>
  <div><input type="submit" value="submit" ></div>
</form>

I am trying to send "user" and "email" together to the database now. What happens actually is that everytime I click on submit button of the survey.php page, the "user" variable gets empty.

CodePudding user response:

You have to test your posts DATA and user Sesssion. In your PHP code, you can have something like that

<?php
session_start();
if(isset($_POST['user']))
  $_SESSION['user'] = $_POST['user'];
if(isset($_POST['email']))
  $_SESSION['email'] = $_POST['email'];
if(isset($_SESSION['user']) AND isset($_SESSION['email'])){
   $sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$_SESSION['user']', '$_SESSION['email']');";
  echo $sql;
}


If you don't want to use sessions, you can play with your form like this :

$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$user', '$email');";
echo $sql;
}
<form action="survey.php" method="post">
  <div><input type="text" name="email"></div>
  <div><input type="submit" value="submit" ></div>
  <input type="hidden" name="user" value="<?php echo $user; ?>">
</form>

CodePudding user response:

You have $user and $email as variable then why are you putting them as strings? The below code should work -

$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '" . $user . "', '" . $email . "');";
echo $sql;
}
<form action="survey.php" method="post">
  <div><input type="text" name="email"></div>
  <div><input type="submit" value="submit" ></div>
</form>
  • Related