1

I have an array like this

array([0]=> 'email@email.com', [1]=> 'email2@email.com', [2]=> 'email3@email.com');

I also have a table with hunders of emails on it.

I want to be able to delete all of these emails apart from the ones that are in the array.

I tried this code but nothing happens:

    $emails = join(', ', $emails);
    $sql = "DELETE FROM emails WHERE customer_id='".$id."' AND email NOT IN(".$emails.")";
    $query = $this->db->query($sql);

Can anyone tell me where I am going wrong?

Thanks

Peter

Peter Stuart
  • 2,292
  • 6
  • 40
  • 72
  • You need to convert array to textual form like @Omesh proposed in his answer – rkosegi Sep 06 '12 at 13:35
  • I hope you are certain that the array elements cannot contain SQL. Otherwise, look into [prepared statements](http://stackoverflow.com/a/60496/623041). – eggyal Sep 06 '12 at 13:55

6 Answers6

4

You need to use implode function in php to import covert array to string.

Also need to enclose string values of email in quotes:

$sql = "DELETE FROM emails WHERE customer_id='".$id."' AND 
        email NOT IN('".implode("','",$emails)."')";
Omesh
  • 26,034
  • 6
  • 40
  • 50
3

Maybe:

$emails = implode("', '", $emails);
$sql = "DELETE FROM emails WHERE customer_id='".$id."' AND email NOT IN('".$emails."')";
$query = $this->db->query($sql);
Mihai Iorga
  • 38,217
  • 14
  • 107
  • 106
  • @PeterStuart The difference is in the `implode` and that it will encapsulate each email address in single quotes nicely. +1 (I read it three times before I noticed the difference) – Fluffeh Sep 06 '12 at 13:37
0

You're missing quotes:

$emails = implode("', '", $emails);
$sql = "DELETE FROM emails WHERE customer_id='".$id."' AND email NOT IN('".$emails."')";
$query = $this->db->query($sql);
Matt S
  • 14,406
  • 4
  • 52
  • 75
0

Your array contains literals, but these aren't each individually being surrounded by quotes for your IN list.

Sepster
  • 4,731
  • 18
  • 38
0

It's more likely that you're not wrapping the individual emails with quotes in the query. mysql_error should have picked that up though surely?

$emails = join('", "', $emails);
$sql = 'DELETE FROM emails WHERE customer_id="'.$id.'" AND email NOT IN("'.$emails.'")';
$query = $this->db->query($sql);

Try echoing out $sql and see what you get (post it here if it doesnt make much sense).

EDIT: How dare 2 people post the same answer as me while I'm typing my answer! >:|

HughieW
  • 131
  • 1
  • 4
  • 14
0

please try this.

$emails = join(',', $emails);
To avoid comma in last ,
$emails=trim($emails,',');
$sql = "DELETE FROM emails WHERE customer_id='".$id."' AND email NOT IN(".$emails.")";
$res = $this->db->query($sql);
jeeva
  • 1,501
  • 2
  • 15
  • 23