Website connecting with database on load (should on submit)

时间:2019-04-16 22:24:59

标签: php mysql

I want my website to connect to a mysql database once the form is filled out. However the connection is made and the form is sent once the page is loaded.

    if($_SERVER["REQUEST_METHOD"] == "POST") {
    if(empty($_POST["username"])){
        $usernameError = "Username is required";
        $foundErrors = true;
        }
           else{
                $username = clearUserInputs($_POST["username"]);
            }
        }    

function clearUserInputs($data){
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
if($foundErrors == false) {
        $servername = "localhost";
        $dbusername = "root";
        $dbpassword = "";
        $databasename = "cmetmarketplace"; 
    // PHP code to save form data to the MySQL database

try {
    $conn = new PDO("mysql:host=$servername;dbname=$databasename",
                      $dbusername, $dbpassword);

   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected succesfully <br>";

    $stmt = $conn->prepare("INSERT INTO users (username, PASSWORD, email, title, gender, dob) 
VALUES (:username, :PASSWORD, :email, :title, :gender, :dob)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':PASSWORD', $password);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':gender', $gender);
$stmt->bindParam(':dob', $dob);
$stmt->execute();

 echo "New account $username $password $email created successfully";
     }  
     catch(PDOException $e)
     {
         $errorkey = "Integrity constraint violation: 1062 Duplicate 
 entry";
        if(strpos($e->getMessage(), $errorkey) > 0) {
            $usernameError = "Username already exists";
        }
        else {
        echo "Connection failed: " . $e->getMessage();
        }
    }
$conn = null;
}   
?>

<table class="registration-table">
          <th>Signup Form</th>
        <form method="POST" onsubmit="validate(this)" action="<?php echo 
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
             <tr>
 <td>Username</td>
              <td><input type="text" maxlength="32" name="username" 
 value="<?php echo $username; ?>"></td>
                <td><span class="error"> <?php echo $usernameError; ?> 
 </span></td> 
            </tr>

So it should only connect once the form is filled out but it loads on the page load. Also sorry about the formatting, first time using this new editor

0 个答案:

没有答案