0

here is my database:

table 1: dog
   column 1: email
   column 2: password

table 2: cat
   column 1: email
   column 2: password

i want to check if a string or data already exists or not in a column from two databases:

//check if email exists in either dog or cat.
$stmt = $dbh->prepare("SELECT email FROM dog AND cat WHERE email = :email");
$stmt->bindParam(':email', $email);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);

//if the email exists in either dog or cat, echo the "taken" message below
if($row['email'] == $email) {
   echo "sorry, the email is taken already!";
}

but it is not working for me. how can i make it work?

1
  • in a column of both is OR not AND Commented Apr 10, 2017 at 1:11

2 Answers 2

3

The SQL syntax is not valid.

We can test the return from prepare, and if it's FALSE, then we know an error occurred.

Here's an example:

  //check if email exists in either dog or cat.
  $sql = "SELECT 'dog' AS src, d.email FROM dog d WHERE d.email = :demail
           UNION ALL
          SELECT 'cat' AS src, c.email FROM cat c WHERE c.email = :cemail";

  if ($stmt = $dbh->prepare($sql)) {
      $stmt->bindParam(':demail', $email);
      $stmt->bindParam(':cemail', $email);
      $stmt->execute();
     ...

  } else {
      // handle error condition
  }
Sign up to request clarification or add additional context in comments.

3 Comments

I do believe you either want to remove the quotes from around the dog and cat columns or use ticks `.
@Fred-ii-: The usage of single quotes around the string literals is what I intended. The src column is intended to be a discriminator column... to identify (on each row returned) which SELECT returned which row. Perhaps my choice of literal values ('dog' and 'cat') was confusing. It's not necessary to return the src column at all, but its a pattern we use frequently with UNION ALL queries.
TBH; I wasn't 100% sure about the quotes. You may be right though and do believe I have seen that type of syntax before. If the OP says there was an error, then the quotes might need to be removed.
0

The AND operator is used for boolean expressions in the WHERE clause and in a JOIN condition.

You're looking for UNION. It combines results from queries that have similar columns.

SELECT email
FROM dog
WHERE email = :email
UNION
SELECT email
FROM cat
WHERE email = :email

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.