PHP PDO rowCount不工作?我认为
问题描述:
所以我在一个特定的表,其中的用户名是已在数据库中,像这样抓行量:PHP PDO rowCount不工作?我认为
$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)
希望这有助于你。
干杯!
“不工作”是什么意思? – Chris
这不是抓行数。 –
你没有取任何东西。你缺少$ result = $ second_sql-> fetchAll(); – happymacarts