正在尝试查找数据库中是否存在行。这段代码总是返回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]));
}
发布于 2019-06-22 15:47:32
我同意user3783243的观点,rowCount并不总是与SELECT一起工作(参见PHP Manual->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;
}
这已被证明是可靠的。
发布于 2019-06-21 09:17:51
这段代码:
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;
}
}
发布于 2019-06-21 12:41:41
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;
}
}
https://stackoverflow.com/questions/56695649
复制相似问题