i need help in following query,

how to check this email alreadyexist in our db or not.

var_dump($email);
       output: array(2) {
           [0]=>
        string(22) "xxxx7@gmail.com"
       [1]=>
        string(19) "yyyyy@gmail.com"
      }
     foreach($email as $em)
      {

       $sql = "SELECT * 
   from sf_guard_user sf,personal pi
       where pi.user_id = sf.id
     and sf.email_address = '$em'

        ";

  $query = $db->prepare($sql);
  $query->execute();
 $alreadyexist[$count++] = $query->fetchAll();


        }

this two emails exist in our db. but fectching only one array,

plz help me.what is the problem in my foreach loop.

Recommended Answers

All 3 Replies

If you need to know only whether email exists or not, use COUNT(*) in your query and use fetchColumn() to get the number of rows found:

foreach($email as $em)
{
    $sql = "SELECT COUNT(*)
    from sf_guard_user sf,personal pi
    where pi.user_id = sf.id
    and sf.email_address = '$em'
    ";
    $query = $db->prepare($sql);
    $query->execute();

    // change this to suit your needs
    if($query->fetchColumn() > 0) {
        echo "#em already exists<br>";
    } else {
        echo "#em does not exist<br>";
    }
}

Not really related to your question, but this may save you some headaches. It looks like you're trying to make sure each result row is saved in the next index in the $alreadyexist array. You can do this more easily with:

$alreadyexist[] = $query->fetchAll();

It will automatically assign $query->fetchAll() to the next index in your array.

There are really (really) few occasions when a query inside a loop is needed. In this case it seems like you taking the emails (sf.email_address as you say) from a query above; in that case a single join query in indexes would do the job. Even if you retrieved this list of mails from other means you could have use the same join logic (Of course with UNION avoiding the IN clause e.g: SELECT 'first@example.com' AS email UNION SELECT 'second@example.com' AS email )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.