Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

428
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda