PHP首先将数据发送到数据库然后验证

时间:2016-01-08 14:36:15

标签: php mysql database validation email

我遇到了电子邮件验证问题。

电子邮件验证工作正常但它首先发送表单,如果我刷新页面并再次发送相同的数据,则验证。 为什么在它发送之前没有验证?

我的代码:

<?php
include_once 'init.inc.php';

// database connection

error_reporting(E_ALL);

// function for Registration

function regUser($db)
{
 $password = password_hash($_POST['password3'], PASSWORD_BCRYPT);
 $sql = "INSERT INTO users SET username = '{$_POST['username']}', email = '{$_POST['email']}', password = '$password', laender = '{$_POST['selection']}'";
 $result = $db->query($sql);
 return $result;
}

// function for emailValidation

function emailValidate()
{
 $email1 = $_POST['email'];
 $email1 = filter_var($email1, FILTER_SANITIZE_EMAIL);
 if (!filter_var($email1, FILTER_VALIDATE_EMAIL))
 {
  return true;
 }
 else
 {
  return false;
 }
}

// function to check if username already registered

function usernameExists($db)
{
 $sql = "SELECT username FROM users WHERE username='" . $_POST['username'] . "'";
 $result = $db->query($sql);
 if (mysqli_num_rows($result) > 0)
 {
  return true;
 }
 else
 {
  return false;
 }
}

// function to check if email already exists in database

function emailExists($db)
{

 // var_dump(emailExists($db));

 $sql = "SELECT email FROM users WHERE email = '" . $_POST['email'] . "'";
 $result = $db->query($sql);
 if (mysqli_num_rows($result) > 0)
 {
  return true;
 }
 else
 {
  return false;
 }
}

// sending data to database

if (isset($_POST['submit']))
{

 // var_dump(usernameExists($db));
 // var_dump(emailExists($db));

 if (emailValidate() === false)
 {
 }
 else
 {
  echo 'Please enter a valid email adress';
 }

 if (usernameExists($db) === false && emailExists($db) === false)
 {
  regUser($db);
 }
 else
 {
  die("Username / Email already exists!");
 }
}

用户名和电子邮件存在功能正常。 提交表单后,只有电子邮件验证才会生效。

2 个答案:

答案 0 :(得分:0)

这样做:

element.all(by.model('config.eTypes[$index]')).then(function(arr){
     arr[0].sendKeys('cat');
     arr[1].sendKeys('ball');
     arr[2].sendKeys('bat');
 });

另外,你可以这样做:

if(emailValidate() === false){

}else {
    die( 'Please enter a valid email adress');//use die while not echo, otherwise the php will keep on running even the email is wrong

}

答案 1 :(得分:0)

您可能需要重新订购一些条件检查代码,以便在电子邮件本身有效后检查数据库 ONLY 中是否存在电子邮件/用户名:

if (isset($_POST['submit']))
{
    // email address is not valid, show error message
    if (emailValidate() !== false)
    {
        echo 'Please enter a valid email adress';
    }
    // email address is valid. Now check if it exists in the DB
    else
    {
        if ( (usernameExists($db) === false) && (emailExists($db) === false))
        {
            regUser($db);
        }
        else
        {
            // you can also use echo error in place of die() here
            die("Username / Email already exists!");
        } 
    }
}