Jump to content

Check array against DB


guitarist

Recommended Posts

Hi all!

 

I'm developing a crude mailing list thingymajig (completely legit, I promise!!).

 

At the moment, I have single email subscription in way of a single field form. The email is entered, checked against the database, and subscribed if it is not there. If it is there, an alert is displayed saying 'email already subscribed'. Great.

 

Now I'm taking things further with a text field and coding hich can extract email addresses from a block of text. No, this isn't so I can harvest email addresses illegitimately, it's because I get asked to add chunks of addresses at a time, and at the moment I have to do this manually, one-by-one.

 

I have the code working to extract the email addresses from the text to an array, but now I'm stuck at the duplication check.

 

I think what I'm asking is: how would it be possible to check each address in the array against the database and highlight any duplicates (I'll ultimately be looking to colour the duplicates and new addresses differently, show the number of new addresses to be added, and have a final 'do it' button which will add them...but I can get there on my own once I learn how to check for dupes!)

 

Hopefully someone can give me a nudge in the right direction :)

 

Many thanks!!

Link to comment
https://forums.phpfreaks.com/topic/234184-check-array-against-db/
Share on other sites

Not tested, but should give you an idea on approach

 

//Convert array of new emails so original value is key and escaped value is value
$newEmailsAry = array_fill_keys($newEmailsAry, $newEmailsAry);
foreach($newEmailsAry as $key => $value)
{
    $newEmailsAry[$key] = "'" . mysql_real_escape_string($value) "'";
}

//Query to find existing records
$query = "SELECT email FROM table WHERE email IN (" . implode(", ", $newEmailsAry) . ")";
$result = mysql_query($query);

//Create array of existing values
$existingEmails = array();
while($row = mysql_fetch_assoc($result))
{
    $existingEmailsAry[] = $row['email'];
}

//Remove existing values from user entered array
$newEmailsAry = array_diff($newEmailsAry, $existingEmailsAry);

//Create query to insert only new emails
$query = "INSERT INTO table (`email`)  VALUES (" . implode("), (", $newEmailsAry) . ")";
$result = mysql_query($query);

//Ouput results
echo "The following emails already existed in the db<br>\n";
echo "<ul>\n";
foreach($existingEmailsAry as $email)
{
    echo "<li>{$email}</li>\n";
}
echo "</ul>\n";

echo "The following emails were added to the db<br>\n";
echo "<ul>\n";
foreach($newEmailsAry as $email)
{
    echo "<li>{$email}</li>\n";
}
echo "</ul>\n";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.