Question

I have having a difficult time trying to determine if an email exists in my database table. Currently, it seems to skip the check and insert the email data to the db. It does this even if the email exists in the database.

Any ideas on what I'm doing wrong? I've tried a number of ways, but so far all of them "ignore" the verification step and inserts the duplicate data

Here is my code:

 <?php
 $con=mysqli_connect("localhost","usr1","123456%%","db1");
 // Check conn
 if (mysqli_connect_errno())
   {
   echo "Deu merda ao conectar ao MySQL: " . mysqli_connect_error();
   }

 //query to insert data to db
 $sql="INSERT INTO workshops (nome, email, curso, telefone, semestre, workshop)
      VALUES('$_POST[nome]','$_POST[email]','$_POST[curso]','$_POST[telefone]','$_POST[semestre]'     ,'$_POST[workshop]')";

 //stores email in a var
 $email = $_POST['email'];

 //query to look up for the email
 $query = mysqli_query("SELECT `email` FROM `workshops` WHERE `email` = '$email'");

 //runs $query to see if it finds any result
 if(mysqli_num_rows($query) > 0) {
 echo 'Email already registered'.mysqli_error();
 mysqli_close($con);

 } else {
mysqli_query($con,$sql);
echo "We received your request, thank you!";

//blah blah blah email in portuguese
$assunto = "Confirmaçãoao de inscrição";
$mensagem = "<h1>Obrigado!</h1><br>Recebemos sua inscrição no workshop" .      $_POST['workshop'] . ". <br> Iremos entrar em contato em breve para confirmar sua presença.";
    $from = "contato@mult13.com";
$headers = "From:". $from;
mail($_POST['email'], $assunto, $mensagem, $headers);
mysqli_close($con);
 }
 ?> 
Was it helpful?

Solution

The mysqli_query you are using to check if the email exists needs a reference to the mysql connection.

Change this line:

//query to look up for the email
$query = mysqli_query("SELECT `email` FROM `workshops` WHERE `email` = '$email'");

to this:

//query to look up for the email
$query = mysqli_query($con, "SELECT `email` FROM `workshops` WHERE `email` = '$email'");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top