0

I am trying to set up a website registration page that will post to my MySQL database

I have the following file, mypage.php, coded as follows

<!DOCTYPE html>
<?php 

            $dbServername = "mysite.com";
            $dbUsername = "username";
            $dbPassword = "12345";
            $dbName = "databasename";

            $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if($conn){ echo "Connected!";}     

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    $firstname   = mysqli_real_escape_string($_POST['firstname']);
    $lastname    = mysqli_real_escape_string($_POST['lastname']);
}
          

$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$firstname', '$lastname')";

mysqli_query($conn, $sql);
mysqli_close($conn);
      
?>


<html lang="en">
  
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="style/styles.css" />
    <!--<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>-->
    <link rel="shortcut icon" href="#" />
    <meta
      name="description"
      content="content here"
    />

    <title>Title | Pagename</title>
  </head>

  <body>
    <nav class="nav">
      <div class="container">
        <div class="row">
          <div class="col-md-4">
            <span
              ><a href="index.html" class="logo"
                >Name </a
              ></span
            >
            <span class="logo2"
              >Some text.</span
            >
          </div>
          <div class="col-md-8 menu-padding">
            <span class="menu menu-span"
              ><a href="index.html" class="menu-link">Home</a>
            </span>
            <span class="menu menu-span">
              <a href="about.html" class="menu-link">About</a>
            </span>
            <span class="menu menu-span"
              ><a href="search.html" class="menu-link active">Search</a></span
            >
            <span class="menu menu-span"
              ><a href="contact.html" class="menu-link">Contact</a></span
            >

            <span class="menu menu-span language">
              <a href="../spanish/inicio-esp.html" class="menu-link">Español</a>
            </span>
            <span class="menu menu-span language"
              ><a href="../portuguese/inicio-port.html" class="menu-link"
                >Português</a
              ></span
            >
          </div>
        </div>
      </div>
    </nav>

    <div id="registrationOne">
    <div class="container">


<form name="regForm" method="post" action=<?php echo $_SERVER['PHP_SELF'];?>>
<div class="row">
  <div class="col-md-6">
              <label for="">First Name:</label>
              <input name="firstname" type="text" class="form-control" />
            </div>
            <div class="col-md-6">
              <label for="">Last Name:</label>
              <input name="lastname" type="text" class="form-control" />
            </div>

</div>
<button
            name="submitButton"
            type="submit"
            class="btn btn-primary"
            id="registrationTwo"
            >
            Register
          </button>

</form>
        
    </div>
    </div>
  
  </body>
  <script src="script/index.js"></script>
  
  </html>

And the following javascript file, index.js, coded as follows

function validateRegForm(event) {
  event.preventDefault();

  let first = document.forms["regForm"]["firstname"].value;
  let last = document.forms["regForm"]["lastname"].value;

  if (first.length < 2) {
    alert("Please enter a first name at least of at least two characters");
    return false;
  } else if (last.length < 2) {
    alert("Please enter a last name at least of at least two characters");
    return false;
  } else {
    return true;
  }
}

let regClick = document.getElementById("registrationTwo");
regClick.addEventListener("click", validateRegForm);


function thankReg() {
  if (validateRegForm() === true) {
    let regOneElement = document.getElementById("registrationOne");
    regOneElement.innerHTML = `<div class="row">
<div class="col-md-12">
<h2 class="thankYouReg">Thank you for registering with Pro.Social.<br /><br />Please check your email for your unique search link to get started. <br /><br />If you do not receive an email from us in the next few minutes, please contact us via the Contact page.</h2>
</div>
</div>`;
  }
}
thankReg();

When I load the page, it shows "Connected!" at the top, so the connection is ok. The form validation works as expected, but when I click on the "Register" button, nothing happens (i.e., the innerhtml doesn't change and nothing is posted to the MySQL database). However, if I refresh the page, blank rows appear in the database.

Could someone please advise?

Many thanks in advance.

ASL
  • 15
  • 3
  • Any errors in the console? Did you try to use the debugger to see if `validateRegForm()` is called? These questions relate to [the browser developer tools](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools), an essential tool when creating code like this. – KIKO Software Jun 25 '22 at 15:23
  • 1
    Your `mysqli_query($conn, $sql);` should be within your `if ($_SERVER["REQUEST_METHOD"] == "POST"){` condition, otherwise it's always executed. You should also get notifications of "undefined variable" if you load the page without form submission -- if not, your error reporting off (and you should turn it on). – Markus AO Jun 25 '22 at 15:29
  • Your script is vulnerable to [SQL Injection Attack](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even if [you are escaping variables, its not safe](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string%5D)! You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either MYSQLI or PDO instead of concatenating user provided values into the query. – Barmar Jun 25 '22 at 15:35
  • In `if (validateRegForm() === true)` there is no need to check `=== true` since `validateRegForm` returns a boolean. (`true === true` and `true`) and (`false === true` and `false`) do the same but with longer code and by double-checking the value (one to resolve the condition and one to resolve the if, instead of directly resolve the if). – Doc Jun 25 '22 at 16:20
  • Please edit your post to focus on the problem/question - new readers don’t need the history (the question edit history has that), just a single coherent question. – AD7six Jun 27 '22 at 12:20

2 Answers2

1

event.preventDefault(); prevents the form from submitting. You should only do this if validation fails.

function validateRegForm(event) {
  let valid = true;
  let first = document.forms["regForm"]["firstname"].value;
  let last = document.forms["regForm"]["lastname"].value;

  if (first.length < 2) {
    alert("Please enter a first name at least of at least two characters");
    valid = false;
  } else if (last.length < 2) {
    alert("Please enter a last name at least of at least two characters");
    valid = false;
  }
  if (!valid) {
    event.preventDefault();
  }
}

You could avoid this by simply putting minlength="2" in your <input> elements.

You shouldn't call validateRegForm() from thankReg(), since there's no event to pass as the argument. I'm not sure why you're calling this at top-level in the first place, since that runs before the form is submitted.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

let's see if I can be of help for you.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//enter your code for connecting to the DB after you have verified that there are POSTS


$dbServername = "mysite.com";
$dbUsername = "username";
$dbPassword = "12345";
$dbName = "databasename";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if($conn){ echo "Connected!";}

//mysqli_real_escape_string requires knowing what kind of carset the database is using so it should be put like this.

$firstname   = mysqli_real_escape_string($conn, $_POST['firstname']);
$lastname    = mysqli_real_escape_string($conn, $_POST['lastname']);

$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$firstname', '$lastname')";

mysqli_query($conn, $sql);
mysqli_close($conn);
}
?>
  • Thanks, this worked! I also changed the js per @Barmar's suggestion. Then, I added unset($_POST); and header('Location:'.$_SERVER['PHP_SELF']); to the bottom of the php so it wouldn't submit duplicate rows on page refresh. The problem is now that the data posts, the innerHTML shows up, but then the page keeps refreshing. I've tried multiple different tweaks to either stop the page from refreshing or to redirect it -- adding return false, window.location.replace(), nesting the innerHTML function in the validating function, etc. -- but nothing works and it keeps refreshing. Any ideas? – ASL Jun 28 '22 at 13:56