0

Hy I'm trying to validate the email address in a registration form. I want to check if the address exists in the database. this is my first time with php and i have no idea how to. And i tried to add in my code and error msg, if the email has bad characters.

<?php


$dbhost = "localhost";
$dbusername = "test";
$dbpassword = "tester";
$database_name = "dbtest";


$link = mysql_connect("$dbhost", "$dbusername", "$dbpassword");
if(!$link){ die('Could not connect: ' . mysql_error());}

$db_selected = mysql_select_db("$database_name",$link);
if(!$db_selected){ die('Can\'t use foo: ' . mysql_error());}
            

        $email = strip_tags($_POST['email']);
        $verzija = strip_tags($_POST['mydropdown2']);
        $model = strip_tags($_POST['mydropdown']);
        
        $sql = mysql_query("INSERT INTO novice (naslov, podnaslov, vsebina, objavljeno)
                            VALUES ('$email', '$verzija', '$model', now())
                            ");

if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}





// close connection

?>
<form action="insert.php" method="post">
        <label for="model">Phone model:</label>
        <select required aria-required="true" id="model" name="mydropdown">
            <option value="">Select...</option>
            <option value="x">x</option>
            <option value="xx">xx</option>
            
        </select>
        <label for="version">IOS version:</label>
        <select required aria-required="true" id="version" name="mydropdown2">
            <option value="">Select...</option>
            <option value="ax">ax</option>
            <option value="bx">bx</option>
            <option value="cx">cx</option>
        </select>
        <p>
            <br>
            <label for="emailAddress">Email Address:</label>
            <input type="text" id="emailAddress" placeholder="Your email..." name="email" required> </p>
        <input type="submit" value="Submit"> </form>

make it.

msoboc4
  • 93
  • 1
  • 2
  • 10
  • Where's the code to check for the email account already? I see the insert... – Option Feb 22 '17 at 08:50
  • 1
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use manual escaping and string interpolation or concatenation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/). Accidentally unescaped data is a serious risk. – tadman Feb 22 '17 at 08:50
  • To check an email validity (server side) you can use filter_var like in this official php doc [example](http://php.net/manual/ro/function.filter-var.php). example: filter_var('bob@example.com', FILTER_VALIDATE_EMAIL); – Dan Ionescu Feb 22 '17 at 08:51
  • Do try and avoid doing things like `x === false`. Most APIs are designed to return logically true values on success, so `if ($x)` is often sufficient. Only go down this path if that's not going to work. – tadman Feb 22 '17 at 08:51
  • 2
    @DanIonescu Please link the official PHP documentation whenever possible. It's substantially higher quality than w3schools. – tadman Feb 22 '17 at 08:52
  • now i have the problem how to post data from my form to the database:$dbhost = "localhost"; $dbusername = "test"; $dbpassword = "test1"; $database_name = "dbtest"; $link = mysql_connect("$dbhost", "$dbusername", "$dbpassword"); if(!$link){ die('Could not connect: ' . mysql_error());} $db_selected = mysql_select_db("$database_name",$link); if(!$db_selected){ die('Can\'t use foo: ' . mysql_error());} – msoboc4 Feb 22 '17 at 09:18
  • Well you are escaping your input, which is good, it's frightening how many people post code that shows no apparent thought to input validation/escaping at all. However I think using prepared queries would be better than the approach you've taken. As for your problem, have you a) done a select on email to see if the address in question is already in the database and b) put a UNIQUE constraint on the email column? – GordonM Feb 22 '17 at 09:30
  • 1
    Why are you mixing mysql_* and mysqli_* functions? And why have you edited your question so that you're using strip_tags instead of mysqli_real_escape_string? Strip tags will not protect you from SQL injection at all! – GordonM Feb 22 '17 at 09:36

1 Answers1

5

Now you are trying to insert and not validating !

Use (using PDO) :

$db = new PDO ("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);

$query = $db -> prepare ("SELECT * FROM test WHERE email = :email");

$query -> execute (array (":email" => $email));

$count = $query -> rowCount();

if($count > "0")
{
 echo "email already exist";
}

And you can use this :

filter_var($email, FILTER_VALIDATE_EMAIL);

To validate email format.

  • now the problem is the to post files in the database, i changed the conncetion to mysli, and now i dont know hot to change the post method – msoboc4 Feb 22 '17 at 09:21
  • @msoboc4 I really didn't understand what you mean ! but you don't need to change post method ! –  Feb 22 '17 at 09:25
  • i edited my code, as you can see above...now the problem is i cant add data to the database, i get some errors: Warning: mysqli_error() expects parameter 1 to be mysqli, – msoboc4 Feb 22 '17 at 09:32
  • There are a number of problems with this. It only takes into account the case where there is precisely 1 and only 1 occurrence of a given email address, it will fail if for whatever reason a given address appears more than once. Additionally it returns far more data than is actually needed. All you need is `SELECT COUNT(1) FROM table WHERE column = :value LIMIT 1` to verify if a given value exists in the table or not. – GordonM Feb 22 '17 at 09:34
  • You can't use mysqli and PDO together ! You have to choose one ! Try my code to validate if the email already exist or not, if not, try to insert data to your database again using PDO by changing the query from SELECT to INSERT ! –  Feb 22 '17 at 09:38
  • @GordonM Basically, you can change it to > 0 ! but if someone try to check if email already exist, mean they don't want more than one in the database ! So you will never have more than one entry with same value in ur database ! –  Feb 22 '17 at 09:40
  • @Lynxis Assuming that the database designer applied a UNIQUE constraint to the email column that's true, but you can't assume anything. If they didn't then there's always the possibility of a race condition allowing the same email address in multiple times, or even just careless editing of the database by some DBA – GordonM Feb 22 '17 at 09:41