0

I try to check if an email address exists in my database for 3 time with this code

$checkEmail = $_POST['email'];

$query = "SELECT email, count(*) $checkEmail FROM participanti GROUP BY email HAVING $checkEmail = 3";
$result = mysql_query($query) or die(mysql_error());
if ($row = mysql_num_rows($result)){

    if ($row[$checkEmail] == 3) {
        echo "NY";
    }
    else{

But on my website it says

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@mail.com FROM participanti GROUP BY email HAVING address@mail.com = 3' at line 1
  • 2
    You are **wide open** to SQL injection attacks, and you **will be hacked** if you haven't been already. Use prepared/parameterized queries to avoid this problem entirely. Your syntax error is that you have stuck `$checkEmail` in where your fields go. – Brad Sep 02 '13 at 17:39
  • $checkEmail is a value, it should have corresponding column name in the query – user4035 Sep 02 '13 at 17:40
  • Then how to check if the email from my form already exists in my database ? – SlowlyDeath Sep 02 '13 at 17:41
  • Please, edit your post, so we won't need to scroll horizontally to read it – user4035 Sep 02 '13 at 17:41
  • @SlowlyDeath Show us the example of the database data and the value of $checkEmail variable. – user4035 Sep 02 '13 at 17:43

2 Answers2

1
$query = "SELECT email, count(*) as total 
FROM participanti 
WHERE email = '$checkEmail' 
GROUP BY email 
HAVING total = 3";
Nico
  • 343
  • 3
  • 7
  • Thanks :D It works, but ... this prevents sql injection ? I want a secure code because this code is used with a script that works with money ... – SlowlyDeath Sep 02 '13 at 17:45
  • It DOES NOT prevent SQL Injection. Use parameterized queries: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Nico Sep 02 '13 at 17:51
0

The problem is that you are giving the column an Invalid name.

You should use something like CntOfEmails or such

so something like

$query = "SELECT email, count(*) CntOfEmails FROM participanti GROUP BY email HAVING CntOfEmails = 3";
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284