I have a form to add email into my database. This is the HTML:

<form action="/store_email_db.php" method="POST">
  <input type="email" class="control" placeholder="Enter your email" required="required" name="customermail">
  <button class="bttn-white active" type="submit"><span class="lnr lnr-location"></span> Subscribe</button>
  <label class="mt10" for="mc-email"></label>
</form>

And this is my php code (in another file) to add it into my database:

$sql = "INSERT INTO contacts(email, insert_date) VALUES('$email', Now())";
if ($conn->query($sql) === TRUE) {
  echo "New record created successfully"; 
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

And I get this blank page:

Blank page

What I would like is to change the html label value below the email box in the main page instead without redirecting to a blank page : enter image description here

2 Answers

1
Hackerokk On

Seems like it is some verbose mode in your database driver, which is give you "Connected Successfully". Disable it, and after that, read something about ajax requests. With ajax you can get info from PHP without refreshing the page.

0
Matthew Vanlandingham On

The action inside of the form redirects to whatever page you put there, and then it is echoing the appropriate stuff on that page. There are a couple different things you can do instead to display the message

  1. I usually put the php code at the top of my file, and then put the same file in the action of the form. Here is what it might look like after this is done:

    <?php
    session_start();
    
    if(isset($_SESSION['msg'])) {
        unset($_SESSION['msg']);
    }
    
    if(isset($_POST['submit'])) {
    
    
        $sql = "INSERT INTO contacts(email, insert_date) VALUES('$email', Now())";
        if ($conn->query($sql) === TRUE) {
          $_SESSION['msg'] = "New record created successfully"; 
        } else {
          $_SESSION['msg'] = "Error: " . $sql . "<br>" . $conn->error;
        }
    }
    ?>
    <form action="same_file.php" method="POST">
      <input type="email" class="control" placeholder="Enter your email" 
        required="required" name="customermail">
        <button class="bttn-white active" type="submit" name="submit"><span class="lnr lnr- 
        location"></span> Subscribe</button>
    <label class="mt10" for="mc-email"></label>
    <div> <?php echo $_SESSION['msg'] ?> </div>
    </form>
    

    A couple things to note: the button has to have the submit name associated with it; the first if statement in the php is used for unsetting the message if there is one when the user visits the page.

  2. OR you can make an ajax request for store_email_db.php when the user clicks the submit button, and display the response in a dynamically created div, but I feel like this method is a bit more difficult to implement.

This code is untested, but I have used something just like it in a website I built so it should work. Hope it helps!