【问题标题】:PHP SELECT from two tables从两个表中选择 PHP
【发布时间】:2017-04-10 01:04:34
【问题描述】:

这是我的数据库:

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

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

我想检查一个字符串或数据是否已经存在于两个数据库的列中:

//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!";
}

但这对我不起作用。我怎样才能让它工作?

【问题讨论】:

  • 在两者的列中是 OR 不是 AND

标签: php mysql database select pdo


【解决方案1】:

SQL 语法无效。

我们可以测试prepare的返回,如果是FALSE,那么我们就知道发生了错误。

这是一个例子:

  //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
  }

【讨论】:

  • 我相信您要么想删除 dogcat 列周围的引号,要么使用刻度 `
  • @Fred-ii-:在字符串文字周围使用单引号是我的意图。 src 列旨在成为鉴别器列...以识别(在返回的每一行上)哪个 SELECT 返回了哪一行。也许我选择的文字值('dog''cat')令人困惑。根本不需要返回 src 列,但它是我们经常用于 UNION ALL 查询的模式。
  • TBH;我不是 100% 确定报价。不过你可能是对的,并且相信我以前见过这种类型的语法。如果 OP 说有错误,那么可能需要删除引号。
【解决方案2】:

AND 运算符用于WHERE 子句和JOIN 条件中的布尔表达式。

您正在寻找UNION。它结合了来自具有相似列的查询的结果。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多