因此,我正在获取特定表中的行数,其中用户名已经在数据库中,如下所示:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
问题是它不起作用。如果您需要更多脚本,请告诉我。
最佳答案
某些数据库不使用 PDO->rowCount()
方法报告行数。
例如 SQLite。
所以不要使用rowCount()
;这样做会降低您的代码的可移植性。
而是在查询中使用 COUNT(*)
函数,并将结果存储在变量中。
最后,使用该变量通过 fetchColumn()
方法获取唯一的列(用户)。
所以你可以玩这个:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
也许您想测试单行的条件:
if ($count == 1)
希望这对您有帮助。
干杯!
关于PHP PDO rowCount 不起作用?我认为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39106715/