Pregunta

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

¿Fue útil?

Solución

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)."')";

Otros consejos

Maybe:

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

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);

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

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! >:|

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top