数据库查询始终返回TRUE

时间:2019-06-21 01:06:55

标签: php mysql

尝试查找数据库中是否存在行。此代码始终返回TRUE。我要添加该行(如果不存在)。 请参见下面的测试代码。

 // CHECK IF RECORD EXISTS
  if (array_key_exists('test', $_GET)) {
    if(coupleRowExists($_GET['male'], $_GET['female'])) {
      echo 'EXISTS';
    } else {
      echo 'Does NOT exist';
    }
  }

  // CHECK DB FOR THIS COUPLE
  function coupleRowExists($male, $female) {
    global $db;
    $sp_couple_exists = "SELECT EXISTS(SELECT 1 FROM `couples` 
                         WHERE male = ? AND female = ? )";
    return ($db->prepare($sp_couple_exists)->execute([$male, $female]));
  }

3 个答案:

答案 0 :(得分:1)

此代码:

return ($db->prepare($sp_couple_exists)->execute([$male, $female]));

成功执行数据库查询时(不一定有结果)将返回true。如果您正确地编写了查询,那将一直存在。

如果您想确定它是否实际返回了一行,那么您将需要检查实际返回的行。

我会对此进行一些修改,以使其返回并更加干净:

function coupleRowExists($male, $female) {
  global $db;
  $sql = "SELECT EXISTS(SELECT 1 FROM couples WHERE male = ? AND female = ?)";
  $db->prepare ($sql);
  $db->execute ([$male, $female]);

  if ($db->rowCount()) {
    return true;
  } else {
    return false;
  }
}

答案 1 :(得分:1)

execute()将仅返回true或false。这是参考链接。 https://www.php.net/manual/en/pdostatement.execute.php

这是相同的修改功能。

function coupleRowExists($male, $female) {
  global $db;
  $sql = "SELECT EXISTS(SELECT 1 FROM couples WHERE male = ? AND female = ?)";
  $db->prepare ($sql);
  $result = $db->execute ([$male, $female]);

  if ($result && $db->rowCount() > 0) {
    return true;
  } else {
    return false;
  }
}

答案 2 :(得分:0)

我同意user3783243的观点,因为rowCount并不总是与SELECT一起使用(请参见PHP手册-> PDOStatement :: rowCount()。他们建议按以下方式使用COUNT:

function coupleRowExists($m, $f) {
    global $db;
    $sp = "SELECT COUNT(*) FROM `couples` WHERE male = ? AND female = ?";
    $stmt = $db->prepare($sp);
    $stmt->execute([$m, $f]);
    $count = $stmt->fetchColumn();
    return $count;
  }

这被证明是可靠的。

相关问题