0

I have put a UNIQUE index on my email column in the database, and when I enter an already registered email the database does not update. so that works well. I now need to tell the user entering an already existing email(on the signup page) that it is already registered and redirect them to the homepage.

Please check my SQL injection code too and correct if there are any errors.

<?php

$fullname = $_POST['fullname'];
$email = $_POST['email'];
$mobilenumber = $_POST['mobilenumber'];

//prevent sql injection
$fullname = stripslashes($fullname);
$email = stripcslashes($email);
$mobilenumber = stripslashes($mobilenumber);
$fullname = mysql_real_escape_string($fullname);
$email = mysql_real_escape_string($email);
$mobilenumber = mysql_real_escape_string($mobilenumber);


//Database Connection

$conn = new mysqli("#","#","#","#");
if($conn->connect_error){
    die('connection Failed : '.$conn->connect_error);
}else{
        $stmt = $conn->prepare("insert into signup(fullname,email,mobilenumber)values(?,?,?)");
        $stmt->bind_param("ssi",$fullname,$email,$mobilenumber);
        $stmt->execute();
        header("Location:thankyou.html");
        $stmt->close();
        $conn->close();

}

?>
  • 1
    if you use a `prepared statement` you do not need nor should use `mysql_real_escape_string` as it can potentially change the the data slightly. Before doing the `insert` statement do a `select` to find that email address - if it exists tell the user otherwise do the insert. – Professor Abronsius Aug 06 '20 at 06:42
  • we can check existing email user multiway using jQuery Ajax on blur event against a database or if you are using frameworks like `CodeIgniter` you can use serverside validation or you need to do manual serverside validation for corephp – Mohsin Marui Aug 06 '20 at 06:43

2 Answers2

1

As per the comment - if you do a simple select before trying to do the insert you can fork the program logic and let the user know.

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( 
        $_POST['fullname'], 
        $_POST['email'], 
        $_POST['mobilenumber'] 
    )){
        
        $fullname = $_POST['fullname'];
        $email = $_POST['email'];
        $mobilenumber = $_POST['mobilenumber'];
        
        
        
        $dbport =   3306;
        $dbhost =   'localhost';
        $dbuser =   'dbo-user-xxx';
        $dbpwd  =   'dbo-pwd-xxx';
        $dbname =   'db-xxx';
        
        
        
        error_reporting( E_ALL );
        mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
        $conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
        
        try{
        
            #check email before insert
            $sql='select `email` from `signup` where `email`=?';
            $stmt=$conn->prepare( $sql );
            $stmt->bind_param('s',$email);
            $stmt->execute();
            $stmt->store_result();
            
            if( $stmt->num_rows==0 ){
                /* email does not exist - perform insert */
                $sql='insert into `signup` ( `fullname`, `email`, `mobilenumber` ) values ( ?, ?, ? )';
                $stmt=$conn->prepare( $sql );
                $stmt->bind_param('sss', $fullname, $email, $mobilenumber );
                $stmt->execute();
                $stmt->close();
                $conn->close();
                
                exit( header('Location: thankyou.html') );
                
            }else{
                /* email does exist - tell user */
                $stmt->free_result();
                $stmt->close();
                
                exit( header('Location: ?error=true&email=true' ) );
            }
            
        }catch( mysqli_sql_exception $e ){
            exit( $e->getMessage() );
        }
    }
?>

Alternatively you can try/catch as before but use the return error code to fork the logic

<?php
    /*
    
        mysql> describe signup;
        +--------------+------------------+------+-----+---------+----------------+
        | Field        | Type             | Null | Key | Default | Extra          |
        +--------------+------------------+------+-----+---------+----------------+
        | id           | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
        | fullname     | varchar(50)      | NO   |     | NULL    |                |
        | email        | varchar(64)      | NO   | UNI | NULL    |                |
        | mobilenumber | varchar(16)      | NO   |     | NULL    |                |
        +--------------+------------------+------+-----+---------+----------------+
        
        mysql> select * from signup;
        +----+----------+-----------------------------+--------------+
        | id | fullname | email                       | mobilenumber |
        +----+----------+-----------------------------+--------------+
        |  1 | fred     | fred.flintstone@bedrock.com | 123          |
        +----+----------+-----------------------------+--------------+
    */




    /* Attempt to insert duplicate - but use error code 1062 to fork the logic */
    $dbport =   3306;
    $dbhost =   'localhost';
    $dbuser =   'dbo-user-xxx';
    $dbpwd  =   'dbo-pwd-xxx';
    $dbname =   'db-xxx';
            
    
    /* same email and phone number but different fullname */
    $email='fred.flintstone@bedrock.com';
    $fullname='freddy boy';
    $mobilenumber=123;
    
    
            
    error_reporting( E_ALL );
    mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
    $conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
    
    try{
    
        $sql='insert into `signup` ( `fullname`, `email`, `mobilenumber` ) values ( ?, ?, ? )';
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param('sss', $fullname, $email, $mobilenumber );
        $stmt->execute();
        

    }catch( mysqli_sql_exception $e ){
        if( $e->getCode()==1062 ){
            /* redirect the user and let them know the email already exists */
            exit( header( sprintf('Location: ?error=%s',$e->getMessage() ) ) );
        }
    }
    
?>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • This works to some extent, once I submit an already registered email it shows this in the address bar `?error=true&email=true`. I need it to show an error message at the top of my HTML – python enthusiast Aug 06 '20 at 08:33
  • how you handle that error situation is up to you. You do not need to set a querystring - it could use cookies or sessions etc - but then you do need to display some sort of message ( which is what I thought you wished anyway ) ~ I simply show you here a mechanism that you can adopt to suit your needs rather than the absolute must do method ;-) – Professor Abronsius Aug 06 '20 at 09:50
  • All is fine, but why do you still expose the error message to the user? The reason why error reporting is disabled by default is that we do not want the user to see the error message. Remove try-catch` and this answer will be really good. – Dharman Aug 06 '20 at 13:24
-1
  // first check the database to make sure 
  // a email does not already exist with the same  email
  $fullname = $_POST['fullname'];
  $email = $_POST['email'];
  $mobilenumber = $_POST['mobilenumber'];

  $user_check_query = "SELECT * FROM signup WHERE email='$email'LIMIT 1";
  $result = mysqli_query($cons, $user_check_query);
  $emailcheck= mysqli_fetch_assoc($result);
  
  if ($emailcheck) { // if email exists
    if ($emailcheck['email'] === $email) {
      array_push($errors, "email already exists");
    header('location: index.php');
    }

  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
     $sql = "insert into 
     signup(fullname,email,mobilenumber)values($fullname,$email,$mobilenumber)";
     $runsql = mysqli_query($cons, $sql);

    if($runsql) {
        header("Location:thankyou.html");
    } else {
        echo"Some thing is wrong";
    }
  }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    simple perhaps but wide open to sql injection – Professor Abronsius Aug 06 '20 at 09:51
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 06 '20 at 13:25