Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

424
Visualizações
PHP Form Submits automatically at page load

My PHP form submits automatically when my page loads. When it submits automatically, my SQL data base register a form submission but with no data recollected.

Not sure how to get it fix.

This is my code.

<?php 
    //connection to database
    $con = mysqli_connect("localhost","subscriber","password","data-Base");

    $emailErr = "";
    $email = "";
    $Email = $_POST['email'];

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
      } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Please enter a Valid Email"; 
        }
      }
    }
    //form submission
    $sql = "INSERT INTO emails (Email) VALUES ('$Email')";
?>
<?php
    // define variables and set to empty values
    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }
    mysqli_close($con);
    if($email){
        $sent = "Thank You for Subscribing";
}
?>

<form id="login" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>" method="post">

    <fieldset id="inputs">
        <input id="username" name="email" type="text" 
        placeholder="Sign up for our newsletter:">    
    </fieldset>

    <fieldset id="actions">
        <input type="submit" id="submit" value="Subscribe">
    </fieldset>

       <div class="email-sent">
            <?php if(!empty($sent)) { echo $sent; } ?> <br>
            <?php echo $emailErr;?>
       </div>
</form>
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Stuff it all into a check, no need to query anything if nothing is submitted, if submitted than do it.

<?php 
if(isset($_POST['submit'])){
    $con = mysqli_connect("localhost","subscriber","password","data-Base");

    $emailErr = "";
    $email = "";
    $Email = $_POST['email'];
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
      } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Please enter a Valid Email"; 
        }
      }
    }
    //form submission
    $sql = "INSERT INTO emails (Email) VALUES ('$Email')";
}
?>
<form action="">
    <input type="text" name="email">
    <input type="submit" name="submit" value="Submit">
</form>

Alternatively, if say you have multiple forms on one page, you can identify which submit button is pushed and act accordingly. In which case you would want to move you $con out on its own and not in that block, otherwise you'd have to add it to each one..

<?php 
if($_POST['submit'] == 'email_submit'){
    $con = mysqli_connect("localhost","subscriber","password","data-Base");

    $emailErr = "";
    $email = "";
    $Email = $_POST['email'];
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
      } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Please enter a Valid Email"; 
        }
      }
    }
    //form submission
    $sql = "INSERT INTO emails (Email) VALUES ('$Email')";
}
?>
<form action="">
    <input type="text" name="email">
    <button type="submit" value="submit" value="email_submit">Submit</button>
</form>

That should work, but as always, no promises :)

over 4 years ago · Santiago Trujillo Relatório

0

Because that's what you're telling it to do. Wrap it in an isset submit. Ideally I'd put your tests in that as well, I'll show after, and give it an error count, if error == 0, then submit.

<?php 
    //connection to database
    $con = mysqli_connect("localhost","subscriber","password","data-Base");
    //if we fail to connect

    $emailErr = "";
    $email = "";
    $Email = $_POST['email'];
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
      } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Please enter a Valid Email"; 
        }
      }
    }
if(isset($_POST['submit'])){
    //form submission
    $sql = "INSERT INTO emails (Email) VALUES ('$Email')";
}
?>
<?php
    // define variables and set to empty values
    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }
    mysqli_close($con);
    if($email){
        $sent = "Thank You for Subscribing";
}
?>

<form id="login" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>" method="post">

Better method, wrap it all in an isset and then validate using an error count

<?php 
    //connection to database
    $con = mysqli_connect("localhost","subscriber","password","data-Base");
    //if we fail to connect

    $emailErr = "";
    $email = "";
    $Email = $_POST['email'];

if(isset($_POST['submit'])){
$errorCount = 0;


      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
        $errorCount++;
      }

      $email = test_input($_POST["email"]);
      // check if e-mail address is well-formed
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Please enter a Valid Email"; 
        $errorCount++;
      }

    if($errorCount == 0){
     //form submission
      $sql = "INSERT INTO emails (Email) VALUES ('$Email')";
    }

}
?>
<?php
    // define variables and set to empty values
    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }
    mysqli_close($con);
    if($email){
        $sent = "Thank You for Subscribing";
}
?>

<form id="login" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>" method="post">
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda