PHP SELECT from two tables

时间:2017-04-10 01:04:34

标签: php mysql database select pdo

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?

2 个答案:

答案 0 :(得分: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
  }

答案 1 :(得分: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