Question

Hi i want to make an insert in my mysql database but first I want to check if the email is not avaible in the table blacklist. If the mail is in the blacklist I want to ignore the insert.

$sqlinsertqueue = "
INSERT INTO queue Set
email = '$email'"
mysql_query($sqlinsertqueue,$db);

My blacklist has also the field email. My tablename from my blacklist is blacklist.

Was it helpful?

Solution 2

Something like this:

$email = mysql_real_escape_string($email);

//check blacklist
$sql = "
SELECT
        COUNT(*)
FROM
        blacklist
WHERE
        email='$email'
";
$result = mysql_query($sql, $db);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}
$row = mysql_fetch_array($result,  MYSQL_NUM);

if ($row[0] == 0)
{
    //insert
    $sqlinsertqueue = "
INSERT INTO queue Set
email = '$email'";
    mysql_query($sqlinsertqueue,$db);    
}

Don't use mysql_* functions - they are deprecated.

OTHER TIPS

Since @EdGibbs deleted his answer before I got to say this, he was on the right track with an INSERT ... SELECT;

INSERT INTO queue (email) 
  SELECT 'dummy@example.com' FROM DUAL
  WHERE 'dummy@example.com' NOT IN (SELECT email from Blacklist);

An SQLfiddle to test with.

You may want to use PDO or MySQLi instead of the deprecated mysql_* api, or at the very least do mysql_escape_string() on the email addresses before inserting them into the SQL query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top