0

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.

4
Contributors
3
Replies
34
Views
4 Years
Discussion Span
Last Post by jkon
0

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>";
    }
}
0

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.

1

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 )

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.